Exemple #1
2
func resolveConfiguration() (*configuration.Configuration, error) {
	var configurationPath string

	if flag.NArg() > 0 {
		configurationPath = flag.Arg(0)
	} else if os.Getenv("REGISTRY_CONFIGURATION_PATH") != "" {
		configurationPath = os.Getenv("REGISTRY_CONFIGURATION_PATH")
	}

	if configurationPath == "" {
		return nil, fmt.Errorf("configuration path unspecified")
	}

	fp, err := os.Open(configurationPath)
	if err != nil {
		return nil, err
	}

	config, err := configuration.Parse(fp)
	if err != nil {
		return nil, fmt.Errorf("error parsing %s: %v", configurationPath, err)
	}

	return config, nil
}
Exemple #2
0
// NewDaemon returns a Daemon instance to be used for testing.
// This will create a directory such as d123456789 in the folder specified by $DEST.
// The daemon will not automatically start.
func NewDaemon(c *check.C) *Daemon {
	dest := os.Getenv("DEST")
	c.Assert(dest, check.Not(check.Equals), "", check.Commentf("Please set the DEST environment variable"))

	id := fmt.Sprintf("d%d", time.Now().UnixNano()%100000000)
	dir := filepath.Join(dest, id)
	daemonFolder, err := filepath.Abs(dir)
	c.Assert(err, check.IsNil, check.Commentf("Could not make %q an absolute path", dir))
	daemonRoot := filepath.Join(daemonFolder, "root")

	c.Assert(os.MkdirAll(daemonRoot, 0755), check.IsNil, check.Commentf("Could not create daemon root %q", dir))

	userlandProxy := true
	if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
		if val, err := strconv.ParseBool(env); err != nil {
			userlandProxy = val
		}
	}

	return &Daemon{
		Command:       "daemon",
		id:            id,
		c:             c,
		folder:        daemonFolder,
		root:          daemonRoot,
		storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"),
		userlandProxy: userlandProxy,
	}
}
Exemple #3
0
// CreateTestFeature creates a random feature to be used during testing.
func CreateTestFeature(t *testing.T) *models.Feature {
	s, err := store.NewMySQLStore(
		os.Getenv("LAIKA_MYSQL_USERNAME"),
		os.Getenv("LAIKA_MYSQL_PASSWORD"),
		os.Getenv("LAIKA_MYSQL_HOST"),
		os.Getenv("LAIKA_MYSQL_PORT"),
		os.Getenv("LAIKA_MYSQL_DBNAME"),
	)
	require.NoError(t, err)

	env, err := s.GetEnvironmentByName("test")
	if err != nil {
		env = &models.Environment{
			Name: "test",
		}
		err = s.CreateEnvironment(env)
		require.NoError(t, err)
	}

	feature := &models.Feature{
		Name: "test_feature" + store.Token(),
		Status: map[string]bool{
			"test": true,
		},
	}

	err = s.CreateFeature(feature)
	require.NoError(t, err)

	return feature
}
func initDefaultCachePath() string {
	xdgCache := os.Getenv("XDG_CACHE_HOME")
	if xdgCache == "" {
		xdgCache = filepath.Join(os.Getenv("HOME"), ".cache")
	}
	return filepath.Join(xdgCache, "bashbrew")
}
Exemple #5
0
func TestBackend_configConnection(t *testing.T) {
	b := Backend()
	d1 := map[string]interface{}{
		"value": os.Getenv("MYSQL_DSN"),
	}
	d2 := map[string]interface{}{
		"connection_url": os.Getenv("MYSQL_DSN"),
	}
	d3 := map[string]interface{}{
		"value":          os.Getenv("MYSQL_DSN"),
		"connection_url": os.Getenv("MYSQL_DSN"),
	}
	d4 := map[string]interface{}{}

	logicaltest.Test(t, logicaltest.TestCase{
		PreCheck: func() { testAccPreCheck(t) },
		Backend:  b,
		Steps: []logicaltest.TestStep{
			testAccStepConfig(t, d1, false),
			testAccStepConfig(t, d2, false),
			testAccStepConfig(t, d3, false),
			testAccStepConfig(t, d4, true),
		},
	})
}
func main() {
	jenkins_address := os.Getenv("JENKINS_URL")
	listen_address := os.Getenv("LISTEN_ADDRESS")

	if listen_address == "" {
		listen_address = "[::]:8080"
	}
	if jenkins_address == "" {
		log.Fatalln("Use environment variables JENKINS_URL and LISTEN_ADDRESS (default \"[::]:8080\")")
	}

	remote, err := url.Parse(jenkins_address)
	if err != nil {
		log.Panic(err)
	}

	proxy := httputil.NewSingleHostReverseProxy(remote)
	http.HandleFunc("/", handler(proxy))

	log.Println("jenkins-authentication-proxy", version, "starting")
	log.Println("Authentication endpoint:", planio_url)
	err = http.ListenAndServe(listen_address, nil)
	if err != nil {
		log.Panic(err)
	}
}
func createPlaybackClient(t *testing.T) (c *Client) {
	c = &Client{
		ConsumerKey:    os.Getenv("RDIO_API_KEY"),
		ConsumerSecret: os.Getenv("RDIO_API_SECRET"),
		Token:          os.Getenv("RDIO_API_TOKEN"),
		TokenSecret:    os.Getenv("RDIO_API_TOKEN_SECRET"),
	}

	if c.ConsumerKey == "" {
		t.Error("Rdio api key is missing (should be in the RDIO_API_KEY environment variable)")
	}

	if c.ConsumerSecret == "" {
		t.Error("Rdio api secret is missing (should be in the RDIO_API_SECRET environment variable)")
	}

	if c.Token == "" {
		t.Error("Rdio api user token is missing (should be in the RDIO_API_TOKEN environment variable)")
	}

	if c.TokenSecret == "" {
		t.Error("Rdio api user secret is missing (should be in the RDIO_API_TOKEN_SECRET environment variable)")
	}

	return c
}
Exemple #8
0
func LookPath(file string) (string, os.Error) {
	exts := []string{}
	if x := os.Getenv(`PATHEXT`); x != `` {
		exts = strings.Split(strings.ToLower(x), `;`, -1)
		for i, e := range exts {
			if e == `` || e[0] != '.' {
				exts[i] = `.` + e
			}
		}
	}
	if strings.Contains(file, `\`) || strings.Contains(file, `/`) {
		if f, ok := canExec(file, exts); ok {
			return f, nil
		}
		return ``, &PathError{file}
	}
	if pathenv := os.Getenv(`PATH`); pathenv == `` {
		if f, ok := canExec(`.\`+file, exts); ok {
			return f, nil
		}
	} else {
		for _, dir := range strings.Split(pathenv, `;`, -1) {
			if f, ok := canExec(dir+`\`+file, exts); ok {
				return f, nil
			}
		}
	}
	return ``, &PathError{file}
}
func init() {
	// read database shit from flatfile here
	// yes, currently this all just goes into an in-memory struct ... I
	// want to move to a 'real database' if this ever becomes serious.

	defaultPort, err := strconv.Atoi(os.Getenv("whatciv_port"))
	if err != nil {
		defaultPort = 80
	}
	// no checking done because blank is completely okay as a default here
	defaultHost := os.Getenv("whatciv_host")
	defaultDatabase := os.Getenv("whatciv_db")
	if len(defaultDatabase) == 0 {
		cwd, err := os.Getwd()
		if err != nil {
			panic("things went really, really wrong.")
		}

		defaultDatabase = fmt.Sprintf("%s/%s", cwd, "data.json")
	}

	flag.IntVarP(&config.Port, "port", "p", defaultPort, "Port to listen on for the web server")
	flag.StringVarP(&config.Host, "host", "H", defaultHost, "Host to listen on for the web server")
	flag.StringVarP(&config.Database, "db", "d", defaultDatabase, "JSON database of civs and strats to load")

	flag.Parse()

	config.HostAndPort = fmt.Sprintf("%s:%d", config.Host, config.Port)
}
Exemple #10
0
// NewClient returns a new client
func NewClient(config *Config) (*Client, error) {
	// bootstrap the config
	defConfig := DefaultConfig()

	switch {
	case len(config.Address) != 0:
	case len(os.Getenv("CONSUL_HTTP_ADDR")) > 0:
		config.Address = os.Getenv("CONSUL_HTTP_ADDR")
	default:
		config.Address = defConfig.Address
	}

	if len(config.Scheme) == 0 {
		config.Scheme = defConfig.Scheme
	}

	if config.HttpClient == nil {
		config.HttpClient = defConfig.HttpClient
	}

	if strings.HasPrefix(config.Address, "unix://") {
		shortStr := strings.TrimPrefix(config.Address, "unix://")
		t := &http.Transport{}
		t.Dial = func(_, _ string) (net.Conn, error) {
			return net.Dial("unix", shortStr)
		}
		config.HttpClient.Transport = t
		config.Address = shortStr
	}

	client := &Client{
		config: *config,
	}
	return client, nil
}
func TestAccVcdSNAT_Basic(t *testing.T) {
	if v := os.Getenv("VCD_EXTERNAL_IP"); v == "" {
		t.Skip("Environment variable VCD_EXTERNAL_IP must be set to run SNAT tests")
		return
	}

	var e govcd.EdgeGateway

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckVcdSNATDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: fmt.Sprintf(testAccCheckVcdSnat_basic, os.Getenv("VCD_EDGE_GATWEWAY"), os.Getenv("VCD_EXTERNAL_IP")),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckVcdSNATExists("vcd_snat.bar", &e),
					resource.TestCheckResourceAttr(
						"vcd_snat.bar", "external_ip", os.Getenv("VCD_EXTERNAL_IP")),
					resource.TestCheckResourceAttr(
						"vcd_snat.bar", "internal_ip", "10.10.102.0/24"),
				),
			},
		},
	})
}
Exemple #12
0
func slackNotify() {
	accessToken := os.Getenv(slackEnv)
	if accessToken == "" {
		log.Fatalf("Missing access token, %s must be set", slackEnv)
	}

	vals := make(url.Values)
	vals.Set("token", accessToken)
	vals.Set("text", fmt.Sprintf("%s\n%s", *title, *message))
	vals.Set("username", "noti")

	if ch := os.Getenv(slackChannelEnv); ch == "" {
		vals.Set("channel", "#random")
	} else {
		vals.Set("channel", ch)
	}

	resp, err := http.PostForm("https://slack.com/api/chat.postMessage", vals)
	if err != nil {
		log.Fatal(err)
	}

	r := make(map[string]interface{})
	if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
		resp.Body.Close()
		log.Fatal(err)
	}
	resp.Body.Close()

	if r["ok"] == false {
		log.Fatal("Slack API error: ", r["error"])
	}
}
Exemple #13
0
func TestLockInChild(t *testing.T) {
	f := os.Getenv("TEST_LOCK_FILE")
	if f == "" {
		// not child
		return
	}
	lock := Lock
	if v, _ := strconv.ParseBool(os.Getenv("TEST_LOCK_PORTABLE")); v {
		lock = lockPortable
	}

	var lk io.Closer
	for scan := bufio.NewScanner(os.Stdin); scan.Scan(); {
		var err error
		switch scan.Text() {
		case "lock":
			lk, err = lock(f)
		case "unlock":
			err = lk.Close()
			lk = nil
		case "exit":
			// Simulate a crash, or at least not unlocking the lock.
			os.Exit(0)
		default:
			err = fmt.Errorf("unexpected child command %q", scan.Text())
		}
		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Println("")
		}
	}
}
Exemple #14
0
// The uppercase and the lowercase are available for the proxy settings.
// See the Go specification for details on these variables. https://golang.org/pkg/net/http/
func getProxyEnv(key string) string {
	proxyValue := os.Getenv(strings.ToUpper(key))
	if proxyValue == "" {
		return os.Getenv(strings.ToLower(key))
	}
	return proxyValue
}
func testAccPreCheck(t *testing.T) {
	sf := os.Getenv("PUBLISH_SETTINGS_FILE")
	if sf != "" {
		publishSettings, err := ioutil.ReadFile(sf)
		if err != nil {
			t.Fatalf("Error reading AZURE_SETTINGS_FILE path: %s", err)
		}

		os.Setenv("AZURE_PUBLISH_SETTINGS", string(publishSettings))
	}

	if v := os.Getenv("AZURE_PUBLISH_SETTINGS"); v == "" {
		subscriptionID := os.Getenv("AZURE_SUBSCRIPTION_ID")
		certificate := os.Getenv("AZURE_CERTIFICATE")

		if subscriptionID == "" || certificate == "" {
			t.Fatal("either AZURE_PUBLISH_SETTINGS, PUBLISH_SETTINGS_FILE, or AZURE_SUBSCRIPTION_ID " +
				"and AZURE_CERTIFICATE must be set for acceptance tests")
		}
	}

	if v := os.Getenv("AZURE_STORAGE"); v == "" {
		t.Fatal("AZURE_STORAGE must be set for acceptance tests")
	}
}
Exemple #16
0
func getJiraOpts() map[string]interface{} {
	user := os.Getenv("USER")
	home := os.Getenv("HOME")
	defaultQueryFields := "summary,created,updated,priority,status,reporter,assignee,labels"
	defaultSort := "priority asc, created"
	defaultMaxResults := 1000

	opts := make(map[string]interface{})
	defaults := map[string]interface{}{
		"user":        user,
		"endpoint":    os.Getenv("JIRA_ENDPOINT"),
		"queryfields": defaultQueryFields,
		"directory":   fmt.Sprintf("%s/.jira.d/templates", home),
		"sort":        defaultSort,
		"max_results": defaultMaxResults,
		"method":      "GET",
		"quiet":       true,
	}

	for k, v := range cliOpts {
		if _, ok := opts[k]; !ok {
			log.Debugf("Setting %q to %#v from cli options", k, v)
			opts[k] = v
		}
	}

	loadConfigs(opts)
	for k, v := range defaults {
		if _, ok := opts[k]; !ok {
			log.Debugf("Setting %q to %#v from defaults", k, v)
			opts[k] = v
		}
	}
	return opts
}
Exemple #17
0
func getSMTPAuth(hasAuth bool, mechs string) (smtp.Auth, *tls.Config, error) {
	if !hasAuth {
		return nil, nil, nil
	}

	username := os.Getenv("SMTP_AUTH_USERNAME")

	for _, mech := range strings.Split(mechs, " ") {
		switch mech {
		case "CRAM-MD5":
			secret := os.Getenv("SMTP_AUTH_SECRET")
			if secret == "" {
				continue
			}
			return smtp.CRAMMD5Auth(username, secret), nil, nil
		case "PLAIN":
			password := os.Getenv("SMTP_AUTH_PASSWORD")
			if password == "" {
				continue
			}
			identity := os.Getenv("SMTP_AUTH_IDENTITY")

			// We need to know the hostname for both auth and TLS.
			host, _, err := net.SplitHostPort(*smtpSmartHost)
			if err != nil {
				return nil, nil, fmt.Errorf("invalid address: %s", err)
			}

			auth := smtp.PlainAuth(identity, username, password, host)
			cfg := &tls.Config{ServerName: host}
			return auth, cfg, nil
		}
	}
	return nil, nil, nil
}
Exemple #18
0
// LookPath searches for an executable binary named file
// in the directories named by the PATH environment variable.
// If file contains a slash, it is tried directly and the PATH is not consulted.
// LookPath also uses PATHEXT environment variable to match
// a suitable candidate.
// The result may be an absolute path or a path relative to the current directory.
func LookPath(file string) (string, error) {
	x := os.Getenv(`PATHEXT`)
	if x == "" {
		x = `.COM;.EXE;.BAT;.CMD`
	}
	exts := []string{}
	for _, e := range strings.Split(strings.ToLower(x), `;`) {
		if e == "" {
			continue
		}
		if e[0] != '.' {
			e = "." + e
		}
		exts = append(exts, e)
	}
	if strings.ContainsAny(file, `:\/`) {
		if f, err := findExecutable(file, exts); err == nil {
			return f, nil
		} else {
			return "", &Error{file, err}
		}
	}
	if f, err := findExecutable(`.\`+file, exts); err == nil {
		return f, nil
	}
	if pathenv := os.Getenv(`PATH`); pathenv != "" {
		for _, dir := range splitList(pathenv) {
			if f, err := findExecutable(dir+`\`+file, exts); err == nil {
				return f, nil
			}
		}
	}
	return "", &Error{file, ErrNotFound}
}
Exemple #19
0
func NewBuilder(goroot *Repo, name string) (*Builder, error) {
	b := &Builder{
		goroot: goroot,
		name:   name,
	}

	// get builderEnv for this tool
	var err error
	if b.env, err = b.builderEnv(name); err != nil {
		return nil, err
	}

	// read keys from keyfile
	fn := ""
	switch runtime.GOOS {
	case "plan9":
		fn = os.Getenv("home")
	case "windows":
		fn = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
	default:
		fn = os.Getenv("HOME")
	}
	fn = filepath.Join(fn, ".gobuildkey")
	if s := fn + "-" + b.name; isFile(s) { // builder-specific file
		fn = s
	}
	c, err := ioutil.ReadFile(fn)
	if err != nil {
		return nil, fmt.Errorf("readKeys %s (%s): %s", b.name, fn, err)
	}
	b.key = string(bytes.TrimSpace(bytes.SplitN(c, []byte("\n"), 2)[0]))
	return b, nil
}
func getImageIDFromConfig(computeClient *gophercloud.ServiceClient, d *schema.ResourceData) (string, error) {
	// If block_device was used, an Image does not need to be specified.
	// If an Image was specified, ignore it
	if _, ok := d.GetOk("block_device"); ok {
		return "", nil
	}

	if imageId := d.Get("image_id").(string); imageId != "" {
		return imageId, nil
	} else {
		// try the OS_IMAGE_ID environment variable
		if v := os.Getenv("OS_IMAGE_ID"); v != "" {
			return v, nil
		}
	}

	imageName := d.Get("image_name").(string)
	if imageName == "" {
		// try the OS_IMAGE_NAME environment variable
		if v := os.Getenv("OS_IMAGE_NAME"); v != "" {
			imageName = v
		}
	}

	if imageName != "" {
		imageId, err := images.IDFromName(computeClient, imageName)
		if err != nil {
			return "", err
		}
		return imageId, nil
	}

	return "", fmt.Errorf("Neither a boot device, image ID, or image name were able to be determined.")
}
Exemple #21
0
func initDefaultConfigPath() string {
	xdgConfig := os.Getenv("XDG_CONFIG_HOME")
	if xdgConfig == "" {
		xdgConfig = filepath.Join(os.Getenv("HOME"), ".config")
	}
	return filepath.Join(xdgConfig, "bashbrew")
}
Exemple #22
0
func authTokenNote(num int) (string, error) {
	n := os.Getenv("USER")

	if n == "" {
		n = os.Getenv("USERNAME")
	}

	if n == "" {
		whoami := exec.Command("whoami")
		whoamiOut, err := whoami.Output()
		if err != nil {
			return "", err
		}
		n = strings.TrimSpace(string(whoamiOut))
	}

	h, err := os.Hostname()
	if err != nil {
		return "", err
	}

	if num > 1 {
		return fmt.Sprintf("hub for %s@%s %d", n, h, num), nil
	}

	return fmt.Sprintf("hub for %s@%s", n, h), nil
}
Exemple #23
0
// InClusterConfig returns a config object which uses the service account
// kubernetes gives to pods. It's intended for clients that expect to be
// running inside a pod running on kuberenetes. It will return an error if
// called from a process not running in a kubernetes environment.
func InClusterConfig() (*Config, error) {
	host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT")
	if len(host) == 0 || len(port) == 0 {
		return nil, fmt.Errorf("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined")
	}

	token, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/" + api.ServiceAccountTokenKey)
	if err != nil {
		return nil, err
	}
	tlsClientConfig := TLSClientConfig{}
	rootCAFile := "/var/run/secrets/kubernetes.io/serviceaccount/" + api.ServiceAccountRootCAKey
	if _, err := util.CertPoolFromFile(rootCAFile); err != nil {
		glog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err)
	} else {
		tlsClientConfig.CAFile = rootCAFile
	}

	return &Config{
		// TODO: switch to using cluster DNS.
		Host:            "https://" + net.JoinHostPort(host, port),
		BearerToken:     string(token),
		TLSClientConfig: tlsClientConfig,
	}, nil
}
Exemple #24
0
func printInfo(resp http.ResponseWriter, req *http.Request) {
	name := os.Getenv("POD_NAME")
	namespace := os.Getenv("POD_NAMESPACE")
	fmt.Fprintf(resp, "Backend Container\n")
	fmt.Fprintf(resp, "Backend Pod Name: %v\n", name)
	fmt.Fprintf(resp, "Backend Namespace: %v\n", namespace)
}
Exemple #25
0
// NewTestServer creates a new initialised Laika httptest.Server. The server
// root credentials are "root" as username and password. It contains an
// environment named "test" with an enabled featured named "test_feature",
// and a user whose username is "user" and password is "password".
func NewTestServer(t *testing.T) *httptest.Server {
	s, err := store.NewMySQLStore(
		os.Getenv("LAIKA_MYSQL_USERNAME"),
		os.Getenv("LAIKA_MYSQL_PASSWORD"),
		os.Getenv("LAIKA_MYSQL_HOST"),
		os.Getenv("LAIKA_MYSQL_PORT"),
		os.Getenv("LAIKA_MYSQL_DBNAME"),
	)
	require.NoError(t, err)

	err = s.Ping()
	require.NoError(t, err)

	err = s.Migrate()
	require.NoError(t, err)

	user := models.User{
		Username:     "******" + store.Token(),
		PasswordHash: "awesome_password",
	}
	err = s.CreateUser(&user)
	require.NoError(t, err)

	server, err := NewServer(ServerConfig{
		Store:        s,
		RootUsername: "******",
		RootPassword: "******",
	})
	require.NoError(t, err)

	return httptest.NewServer(server)
}
Exemple #26
0
// GET /info
func getInfo(c *context, w http.ResponseWriter, r *http.Request) {
	info := dockerclient.Info{
		Containers:        int64(len(c.cluster.Containers())),
		Images:            int64(len(c.cluster.Images().Filter(cluster.ImageFilterOptions{}))),
		DriverStatus:      c.statusHandler.Status(),
		NEventsListener:   int64(c.eventsHandler.Size()),
		Debug:             c.debug,
		MemoryLimit:       true,
		SwapLimit:         true,
		IPv4Forwarding:    true,
		BridgeNfIptables:  true,
		BridgeNfIp6tables: true,
		NCPU:              c.cluster.TotalCpus(),
		MemTotal:          c.cluster.TotalMemory(),
		HttpProxy:         os.Getenv("http_proxy"),
		HttpsProxy:        os.Getenv("https_proxy"),
		NoProxy:           os.Getenv("no_proxy"),
		SystemTime:        time.Now().Format(time.RFC3339Nano),
	}

	if hostname, err := os.Hostname(); err == nil {
		info.Name = hostname
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(info)
}
// GetConnection get a database connection to a given database name, uses environment variables to
// get the hostname, user, password, and port numbers returns a database connection
func GetConnection(database string) (*sql.DB, error) {
	var dbHost, dbUser, dbPort, dbPassword string
	dbHost = os.Getenv("DB_HOST")
	dbUser = os.Getenv("DB_USER")
	dbPort = os.Getenv("DB_PORT")
	dbPassword = os.Getenv("DB_PASSWORD")

	if dbHost == "" || dbUser == "" || dbPort == "" {
		logit.Error.Println("DB_HOST [" + dbHost + "]")
		logit.Error.Println("DB_USER [" + dbUser + "]")
		logit.Error.Println("DB_PORT [" + dbPort + "]")
		logit.Error.Println("error in getting required env vars")
		panic("could not get required env vars")
	}

	var dbConn *sql.DB
	var err error
	if dbPassword != "" {
		//logit.Info.Println("connecting to database " + database + " host=" + dbHost + " user="******" port=" + dbPort + " password="******"postgres", "sslmode=disable user="******" host="+dbHost+" port="+dbPort+" dbname="+database+" password="******"connecting to database " + database + " host=" + dbHost + " user="******" port=" + dbPort)
		dbConn, err = sql.Open("postgres", "sslmode=disable user="******" host="+dbHost+" port="+dbPort+" dbname="+database)
	}
	if err != nil {
		logit.Error.Println(err.Error())
	}
	return dbConn, err
}
Exemple #28
0
func getConfig() (shuttle.Config, error) {
	c, err := parseFlags(shuttle.NewConfig())
	if err != nil {
		return c, err
	}

	if c.MaxAttempts < 1 {
		return c, fmt.Errorf("-max-attempts must be >= 1")
	}

	c.LogsURL = determineLogsURL(os.Getenv("LOGPLEX_URL"), os.Getenv("LOGS_URL"), c.LogsURL)
	oURL, err := validateURL(c.LogsURL)
	if err != nil {
		return c, err
	}

	if oURL.User == nil {
		oURL.User = url.UserPassword("token", c.Appname)
	}

	c.FormatterFunc = determineOutputFormatter(oURL)

	c.LogsURL = oURL.String()

	c.ComputeHeader()

	return c, nil
}
Exemple #29
0
func LoggerFor(prefix string) Logger {

	l := &logger{
		prefix: prefix + ": ",
		pc:     make([]uintptr, 10),
	}

	trace := os.Getenv("TRACE")
	l.traceOn, _ = strconv.ParseBool(trace)
	if !l.traceOn {
		prefixes := strings.Split(trace, ",")
		for _, p := range prefixes {
			if prefix == strings.Trim(p, " ") {
				l.traceOn = true
				break
			}
		}
	}
	if l.traceOn {
		l.traceOut = l.newTraceWriter()
	} else {
		l.traceOut = ioutil.Discard
	}

	printStack := os.Getenv("PRINT_STACK")
	l.printStack, _ = strconv.ParseBool(printStack)

	return l
}
Exemple #30
0
func init() {
	flag.StringVar(&config.Domain, "domain",
		func() string {
			if x := os.Getenv("SKYDNS_DOMAIN"); x != "" {
				return x
			}
			return "skydns.local."
		}(), "domain to anchor requests to (SKYDNS_DOMAIN)")
	flag.StringVar(&config.DnsAddr, "addr",
		func() string {
			if x := os.Getenv("SKYDNS_ADDR"); x != "" {
				return x
			}
			return "127.0.0.1:53"
		}(), "ip:port to bind to (SKYDNS_ADDR)")

	flag.StringVar(&nameserver, "nameserver", "", "nameserver address(es) to forward (non-local) queries to e.g. 8.8.8.8:53,8.8.4.4:53")
	flag.StringVar(&machine, "machines", "http://127.0.0.1:4001", "machine address(es) running etcd")
	flag.StringVar(&config.DNSSEC, "dnssec", "", "basename of DNSSEC key file e.q. Kskydns.local.+005+38250")
	flag.StringVar(&tlskey, "tls-key", "", "TLS Private Key path")
	flag.StringVar(&tlspem, "tls-pem", "", "X509 Certificate")
	flag.DurationVar(&config.ReadTimeout, "rtimeout", 2*time.Second, "read timeout")
	flag.BoolVar(&config.RoundRobin, "round-robin", true, "round robin A/AAAA replies")
	// TTl
	// Minttl
	flag.StringVar(&config.Hostmaster, "hostmaster", "[email protected].", "hostmaster email address to use")
}