<commit_before>package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
)

const proxyHost = "https://api.github.com/"

func main() {
	port := os.Getenv("PORT")

	if port == "" {
		log.Fatal("$PORT must be set")
	}

	token := os.Getenv("AUTH_TOKEN")

	if token == "" {
		log.Fatal("$AUTH_TOKEN must be set")
	}

	http.HandleFunc("/", ProxyFunc)
	http.ListenAndServe(":" + port, nil)
}

func ProxyFunc(w http.ResponseWriter, r *http.Request) {
	u, err := url.Parse(proxyHost)
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	r.Header.Set("Authorization", fmt.Printf("%s OAUTH-TOKEN", os.Getenv("AUTH_TOKEN")))

	proxy := httputil.NewSingleHostReverseProxy(u)
	proxy.ServeHTTP(w, r)
}
<commit_msg>Sprintf not Printf<commit_after>package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
)

const proxyHost = "https://api.github.com/"

func main() {
	port := os.Getenv("PORT")

	if port == "" {
		log.Fatal("$PORT must be set")
	}

	token := os.Getenv("AUTH_TOKEN")

	if token == "" {
		log.Fatal("$AUTH_TOKEN must be set")
	}

	http.HandleFunc("/", ProxyFunc)
	http.ListenAndServe(":" + port, nil)
}

func ProxyFunc(w http.ResponseWriter, r *http.Request) {
	u, err := url.Parse(proxyHost)
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	r.Header.Set("Authorization", fmt.Sprintf("%s OAUTH-TOKEN", os.Getenv("AUTH_TOKEN")))

	proxy := httputil.NewSingleHostReverseProxy(u)
	proxy.ServeHTTP(w, r)
}
<|endoftext|>


<commit_before>// +build appengine

package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
	"time"

	"appengine"
	"appengine/urlfetch"
)

type task struct {
	context appengine.Context
	url     string
	data    url.Values
}

var (
	BOT_TOKEN, HOOK_TOKEN string
	bot                   Bot
	botId, atId, alias    string
	loc                   *time.Location
	outgoing              chan task
)

func readCredentials(file string) (hookToken, botToken string) {
	b, err := ioutil.ReadFile(file)
	if err != nil {
		log.Fatal(err)
	}
	lines := strings.Split(string(b), "\n")
	hookToken, botToken = lines[0], lines[1]
	log.Println(hookToken, botToken)
	return
}

func handleHook(rw http.ResponseWriter, req *http.Request) {
	if req.Method != "POST" {
		return
	}

	token := req.PostFormValue("token")
	if token != HOOK_TOKEN {
		return
	}

	reply(req)
}

func reply(req *http.Request) {
	c := appengine.NewContext(req)
	c.Infof("%v", req.Form)

	channel := req.PostFormValue("channel_id")
	text := req.PostFormValue("text")
	user_id := req.PostFormValue("user_id")

	client := urlfetch.Client(c)
	data := url.Values{"channel": {channel}}

	if strings.Contains(text, "commit") {
		data.Add("text", WhatTheCommit(client))
		outgoing <- task{
			context: c,
			url:     ChatPostMessageApi,
			data:    data,
		}
	} else if strings.Contains(text, bot.User) ||
		strings.Contains(text, bot.UserId) {
		d1 := url.Values{"channel": {channel}, "text": {"稍等"}}
		outgoing <- task{
			context: c,
			url:     ChatPostMessageApi,
			data:    d1,
		}
		text := codeWithAt(user_id)
		d2 := url.Values{"channel": {channel}, "text": {text}}
		outgoing <- task{
			context: c,
			url:     ChatPostMessageApi,
			data:    d2,
		}
	}
}

func worker(outgoing chan task) {
	for task := range outgoing {
		task.context.Infof("%v", task.data)
		_, err := bot.WithClient(urlfetch.Client(task.context)).PostForm(task.url, task.data)
		if err != nil {
			task.context.Errorf("%v", err)
		}
	}
}

func warmUp(rw http.ResponseWriter, req *http.Request) {
	c := appengine.NewContext(req)
	client := urlfetch.Client(c)
	if bot.Token == "" {
		newbot, err := NewBot(client, BOT_TOKEN)
		if err != nil {
			c.Errorf("%v", err)
		} else {
			bot = newbot
			c.Infof("current bot: %#v", bot)
		}
	}
}

func init() {
	log.Println("appengine init")
	HOOK_TOKEN, BOT_TOKEN = readCredentials("CREDENTIALS.appengine")
	outgoing = make(chan task)
	go worker(outgoing)

	http.HandleFunc("/hook", handleHook)
	http.HandleFunc("/_ah/warmup", warmUp)
}
<commit_msg>add more replies<commit_after>// +build appengine

package main

import (
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"strings"
	"time"

	"appengine"
	"appengine/urlfetch"
)

type task struct {
	context appengine.Context
	url     string
	data    url.Values
}

var (
	BOT_TOKEN, HOOK_TOKEN string
	bot                   Bot
	botId, atId, alias    string
	loc                   *time.Location
	outgoing              chan task
)

func readCredentials(file string) (hookToken, botToken string) {
	b, err := ioutil.ReadFile(file)
	if err != nil {
		log.Fatal(err)
	}
	lines := strings.Split(string(b), "\n")
	hookToken, botToken = lines[0], lines[1]
	log.Println(hookToken, botToken)
	return
}

func handleHook(rw http.ResponseWriter, req *http.Request) {
	if req.Method != "POST" {
		return
	}

	token := req.PostFormValue("token")
	if token != HOOK_TOKEN {
		return
	}

	reply(req)
}

func reply(req *http.Request) {
	c := appengine.NewContext(req)
	c.Infof("%v", req.Form)

	channel := req.PostFormValue("channel_id")
	text := req.PostFormValue("text")
	user_id := req.PostFormValue("user_id")

	client := urlfetch.Client(c)
	data := url.Values{"channel": {channel}}

	if strings.Contains(text, "commit") {
		data.Add("text", WhatTheCommit(client))
		outgoing <- task{context: c, url: ChatPostMessageApi, data: data}
	} else if strings.Contains(text, bot.User) ||
		strings.Contains(text, bot.UserId) {
		d1 := url.Values{"channel": {channel}, "text": {"稍等"}}
		outgoing <- task{context: c, url: ChatPostMessageApi, data: d1}

		text := codeWithAt(user_id)
		d2 := url.Values{"channel": {channel}, "text": {text}}
		outgoing <- task{context: c, url: ChatPostMessageApi, data: d2}
	} else if strings.Contains(text, "谢谢") {
		data.Add("text", "不客气 :blush:")
		outgoing <- task{context: c, url: ChatPostMessageApi, data: data}
	} else {
		if rand.Intn(2) > 0 {
			data.Add("text", "呵呵")
		} else {
			data.Add("text", "嘻嘻")
		}
		outgoing <- task{context: c, url: ChatPostMessageApi, data: data}
	}
}

func worker(outgoing chan task) {
	for task := range outgoing {
		task.context.Infof("%v", task.data)
		_, err := bot.WithClient(urlfetch.Client(task.context)).PostForm(task.url, task.data)
		if err != nil {
			task.context.Errorf("%v", err)
		}
	}
}

func warmUp(rw http.ResponseWriter, req *http.Request) {
	c := appengine.NewContext(req)
	client := urlfetch.Client(c)
	if bot.Token == "" {
		newbot, err := NewBot(client, BOT_TOKEN)
		if err != nil {
			c.Errorf("%v", err)
		} else {
			bot = newbot
			c.Infof("current bot: %#v", bot)
		}
	}
}

func init() {
	log.Println("appengine init")
	HOOK_TOKEN, BOT_TOKEN = readCredentials("CREDENTIALS.appengine")
	outgoing = make(chan task)
	go worker(outgoing)

	http.HandleFunc("/hook", handleHook)
	http.HandleFunc("/_ah/warmup", warmUp)
}
<|endoftext|>


<commit_before>// This is the boot2docker management utilty.
package main

import "os"

// keep 3rd-party imports separate from stdlib with an empty line

// The following vars will be injected during the build process.
var (
	Version string
	GitSHA  string
)

func main() {
	// os.Exit will terminate the program at the place of call without running
	// any deferred cleanup statements. It might cause unintended effects. To
	// be safe, we wrap the program in run() and only os.Exit() outside the
	// wrapper. Be careful not to indirectly trigger os.Exit() in the program,
	// notably via log.Fatal() and on flag.Parse() where the default behavior
	// is ExitOnError.
	os.Exit(run())
}

// Run the program and return exit code.
func run() int {
	flags, err := config()
	if err != nil {
		return 1
	}

	switch cmd := flags.Arg(0); cmd {
	case "download":
		return cmdDownload()
	case "init":
		return cmdInit()
	case "up", "start", "boot", "resume":
		return cmdUp()
	case "save", "suspend":
		return cmdSave()
	case "down", "halt", "stop":
		return cmdStop()
	case "poweroff":
		return cmdPoweroff()
	case "restart":
		return cmdRestart()
	case "reset":
		return cmdReset()
	case "delete":
		return cmdDelete()
	case "info":
		return cmdInfo()
	case "status":
		return cmdStatus()
	case "ssh":
		return cmdSSH()
	case "version":
		outf("Client version: %s\nGit commit: %s\n", Version, GitSHA)
		return 0
	case "help":
		flags.Usage()
		return 0
	case "":
		usageShort()
		return 0
	default:
		errf("Unknown command %q\n", cmd)
		usageShort()
		return 1
	}
}
<commit_msg>Removed useless comments.<commit_after>package main

import "os"

// The following vars will be injected during the build process.
var (
	Version string
	GitSHA  string
)

func main() {
	// os.Exit will terminate the program at the place of call without running
	// any deferred cleanup statements. It might cause unintended effects. To
	// be safe, we wrap the program in run() and only os.Exit() outside the
	// wrapper. Be careful not to indirectly trigger os.Exit() in the program,
	// notably via log.Fatal() and on flag.Parse() where the default behavior
	// is ExitOnError.
	os.Exit(run())
}

// Run the program and return exit code.
func run() int {
	flags, err := config()
	if err != nil {
		return 1
	}

	switch cmd := flags.Arg(0); cmd {
	case "download":
		return cmdDownload()
	case "init":
		return cmdInit()
	case "up", "start", "boot", "resume":
		return cmdUp()
	case "save", "suspend":
		return cmdSave()
	case "down", "halt", "stop":
		return cmdStop()
	case "poweroff":
		return cmdPoweroff()
	case "restart":
		return cmdRestart()
	case "reset":
		return cmdReset()
	case "delete":
		return cmdDelete()
	case "info":
		return cmdInfo()
	case "status":
		return cmdStatus()
	case "ssh":
		return cmdSSH()
	case "version":
		outf("Client version: %s\nGit commit: %s\n", Version, GitSHA)
		return 0
	case "help":
		flags.Usage()
		return 0
	case "":
		usageShort()
		return 0
	default:
		errf("Unknown command %q\n", cmd)
		usageShort()
		return 1
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"log"
	"os"
	"sort"

	"github.com/trayio/reaper/candidates"
	"github.com/trayio/reaper/collector"
	"github.com/trayio/reaper/config"

	"github.com/trayio/reaper/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws"
	"github.com/trayio/reaper/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil"
	"github.com/trayio/reaper/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/ec2"
)

var regions = []string{
	"ap-northeast-1",
	"ap-southeast-1",
	"ap-southeast-2",
	"eu-central-1",
	"eu-west-1",
	"sa-east-1",
	"us-east-1",
	"us-west-1",
	"us-west-2",
}

func main() {
	groupTag := flag.String("tag", "group", "Tag name to group instances by")
	configFile := flag.String("c", "conf.js", "Configuration file.")
	dryRun := flag.Bool("dry", false, "Enable dry run.")

	accessId := flag.String("access", "", "AWS access ID")
	secretKey := flag.String("secret", "", "AWS secret key")
	region := flag.String("region", "us-west-1", "AWS region")
	flag.Parse()

	cfg, err := config.New(*configFile)
	if err != nil {
		log.Println("Configuration failed:", err)
		os.Exit(1)
	}

	credentials := aws.DetectCreds(*accessId, *secretKey, "")
	service := ec2.New(
		&aws.Config{
			Region:      *region,
			Credentials: credentials,
		},
	)

	params := &ec2.TerminateInstancesInput{
		DryRun: aws.Boolean(*dryRun),
	}

	group := make(candidates.Group)

	reservations := make([]*ec2.Reservation, 0)
	ch := collector.Dispatch(credentials, regions)

	for result := range ch {
		reservations = append(reservations, result...)
	}

	log.Println(awsutil.StringValue(reservations))

	// []reservation -> []instances ->
	//		PublicIpAddress, PrivateIpAddress
	//		[]*tag -> Key, Value
	for _, reservation := range reservations {
		for _, instance := range reservation.Instances {
			for _, tag := range instance.Tags {
				if *tag.Key == *groupTag && *instance.State.Name == "running" {
					if _, ok := cfg[*tag.Value]; ok {
						info := candidates.Candidate{
							ID:        *instance.InstanceID,
							CreatedAt: *instance.LaunchTime,
						}
						group[*tag.Value] = append(group[*tag.Value], info)
					}
				}
			}
		}
	}

	for tag, hosts := range group {
		oldies := hosts.OlderThan(cfg[tag].Age)

		// oldest instance first
		sort.Sort(oldies)
		sort.Reverse(oldies)

		if cfg[tag].Count >= len(oldies) {
			log.Fatalf("Refusing to terminate all instances in group %s.", tag)
		} else {
			for _, oldie := range oldies[:cfg[tag].Count] {
				log.Printf("Instance %s from %s selected for termination.\n", oldie.ID, tag)
				params.InstanceIDs = append(params.InstanceIDs, aws.String(oldie.ID))
			}
		}
	}

	resp, err := service.TerminateInstances(params)
	if err != nil {
		log.Println("ERROR:", err)
	}
	log.Println(awsutil.StringValue(resp))
}
<commit_msg>Remove debug info<commit_after>package main

import (
	"flag"
	"log"
	"os"
	"sort"

	"github.com/trayio/reaper/candidates"
	"github.com/trayio/reaper/collector"
	"github.com/trayio/reaper/config"

	"github.com/trayio/reaper/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws"
	"github.com/trayio/reaper/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil"
	"github.com/trayio/reaper/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/ec2"
)

var regions = []string{
	"ap-northeast-1",
	"ap-southeast-1",
	"ap-southeast-2",
	"eu-central-1",
	"eu-west-1",
	"sa-east-1",
	"us-east-1",
	"us-west-1",
	"us-west-2",
}

func main() {
	groupTag := flag.String("tag", "group", "Tag name to group instances by")
	configFile := flag.String("c", "conf.js", "Configuration file.")
	dryRun := flag.Bool("dry", false, "Enable dry run.")

	accessId := flag.String("access", "", "AWS access ID")
	secretKey := flag.String("secret", "", "AWS secret key")
	region := flag.String("region", "us-west-1", "AWS region")
	flag.Parse()

	cfg, err := config.New(*configFile)
	if err != nil {
		log.Println("Configuration failed:", err)
		os.Exit(1)
	}

	credentials := aws.DetectCreds(*accessId, *secretKey, "")
	service := ec2.New(
		&aws.Config{
			Region:      *region,
			Credentials: credentials,
		},
	)

	params := &ec2.TerminateInstancesInput{
		DryRun: aws.Boolean(*dryRun),
	}

	group := make(candidates.Group)

	reservations := make([]*ec2.Reservation, 0)
	ch := collector.Dispatch(credentials, regions)

	for result := range ch {
		reservations = append(reservations, result...)
	}

	// []reservation -> []instances ->
	//		PublicIpAddress, PrivateIpAddress
	//		[]*tag -> Key, Value
	for _, reservation := range reservations {
		for _, instance := range reservation.Instances {
			for _, tag := range instance.Tags {
				if *tag.Key == *groupTag && *instance.State.Name == "running" {
					if _, ok := cfg[*tag.Value]; ok {
						info := candidates.Candidate{
							ID:        *instance.InstanceID,
							CreatedAt: *instance.LaunchTime,
						}
						group[*tag.Value] = append(group[*tag.Value], info)
					}
				}
			}
		}
	}

	for tag, hosts := range group {
		oldies := hosts.OlderThan(cfg[tag].Age)

		// oldest instance first
		sort.Sort(oldies)
		sort.Reverse(oldies)

		if cfg[tag].Count >= len(oldies) {
			log.Fatalf("Refusing to terminate all instances in group %s.\n", tag)
		} else {
			for _, oldie := range oldies[:cfg[tag].Count] {
				log.Printf("Instance %s from %s selected for termination.\n", oldie.ID, tag)
				params.InstanceIDs = append(params.InstanceIDs, aws.String(oldie.ID))
			}
		}
	}

	resp, err := service.TerminateInstances(params)
	if err != nil {
		log.Println("ERROR:", err)
	}
	log.Println(awsutil.StringValue(resp))
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/go-chi/chi"
	"github.com/go-chi/chi/middleware"
	"github.com/unrolled/secure"
	"gopkg.in/reportportal/commons-go.v5/commons"
	"gopkg.in/reportportal/commons-go.v5/conf"
	"gopkg.in/reportportal/commons-go.v5/server"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

func main() {

	currDir, e := os.Getwd()
	if nil != e {
		log.Fatalf("Cannot get workdir: %s", e.Error())
	}

	cfg := conf.EmptyConfig()

	rpConf := struct {
		Cfg         *conf.ServerConfig
		StaticsPath string `env:"RP_STATICS_PATH"`
	}{
		Cfg:         cfg,
		StaticsPath: currDir,
	}

	err := conf.LoadConfig(&rpConf)
	if nil != err {
		log.Fatalf("Cannot log app config")
	}

	info := commons.GetBuildInfo()
	info.Name = "Service UI"

	srv := server.New(rpConf.Cfg, info)
	srv.WithRouter(func(router *chi.Mux) {

		//apply compression
		router.Use(middleware.DefaultCompress)
		router.Use(middleware.Logger)

		//content security policy
		csp := map[string][]string{
			"default-src": {"'self'", "data:", "'unsafe-inline'", "*.uservoice.com"},
			"script-src": {
				"'self'",
				"'unsafe-inline'",
				"'unsafe-eval'",
				"status.reportportal.io",
				"www.google-analytics.com",
				"stats.g.doubleclick.net",
				"*.saucelabs.com",
				"*.epam.com",
				"*.uservoice.com",
				"*.rawgit.com",
			},
			"worker-src": {"'self'", "blob:"},
            "font-src": {"'self'", "data:", "fonts.googleapis.com", "fonts.gstatic.com"},
            "style-src-elem": {"'self'", "data:", "'unsafe-inline'", "*.googleapis.com", "*.rawgit.com"},
            "media-src": {"'self'", "*.saucelabs.com"},
			"img-src": {"*", "'self'", "data:", "blob:"},
			"object-src": {"'self'"},
		}

		//apply content security policies
		router.Use(func(next http.Handler) http.Handler {
			return secure.New(secure.Options{
				ContentTypeNosniff:    true,
				BrowserXssFilter:      true,
				ContentSecurityPolicy: buildCSP(csp),
				STSSeconds:            315360000,
				STSIncludeSubdomains:  true,
				STSPreload:            true,
			}).Handler(next)
		})

		err := os.Chdir(rpConf.StaticsPath)
		if nil != err {
			log.Fatalf("Dir %s not found", rpConf.StaticsPath)
		}

		router.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			//trim query params
			ext := filepath.Ext(trimQuery(r.URL.String(), "?"))

			// never cache html
			if "/" == r.URL.String() || ".html" == ext {
				w.Header().Add("Cache-Control", "no-cache")
			}

			http.FileServer(http.Dir(rpConf.StaticsPath)).ServeHTTP(&redirectingRW{ResponseWriter: w, Request: r}, r)
		}))

	})

	srv.StartServer()

}

func trimQuery(s string, sep string) string {
	sepIndex := strings.Index(s, sep)
	if -1 != sepIndex {
		return s[:sepIndex]
	}
	return s
}

func buildCSP(csp map[string][]string) string {
	var instr []string
	for k, v := range csp {
		instr = append(instr, k+" "+strings.Join(v, " "))
	}
	return strings.Join(instr, "; ")

}

type redirectingRW struct {
	*http.Request
	http.ResponseWriter
	ignore bool
}

func (hrw *redirectingRW) Header() http.Header {
	return hrw.ResponseWriter.Header()
}

func (hrw *redirectingRW) WriteHeader(status int) {
	if status == 404 {
		hrw.ignore = true
		http.Redirect(hrw.ResponseWriter, hrw.Request, "/ui/#notfound", http.StatusTemporaryRedirect)
	} else {
		hrw.ResponseWriter.WriteHeader(status)
	}

}

func (hrw *redirectingRW) Write(p []byte) (int, error) {
	if hrw.ignore {
		return len(p), nil
	}
	return hrw.ResponseWriter.Write(p)
}
<commit_msg>Update font-src security policy<commit_after>package main

import (
	"github.com/go-chi/chi"
	"github.com/go-chi/chi/middleware"
	"github.com/unrolled/secure"
	"gopkg.in/reportportal/commons-go.v5/commons"
	"gopkg.in/reportportal/commons-go.v5/conf"
	"gopkg.in/reportportal/commons-go.v5/server"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

func main() {

	currDir, e := os.Getwd()
	if nil != e {
		log.Fatalf("Cannot get workdir: %s", e.Error())
	}

	cfg := conf.EmptyConfig()

	rpConf := struct {
		Cfg         *conf.ServerConfig
		StaticsPath string `env:"RP_STATICS_PATH"`
	}{
		Cfg:         cfg,
		StaticsPath: currDir,
	}

	err := conf.LoadConfig(&rpConf)
	if nil != err {
		log.Fatalf("Cannot log app config")
	}

	info := commons.GetBuildInfo()
	info.Name = "Service UI"

	srv := server.New(rpConf.Cfg, info)
	srv.WithRouter(func(router *chi.Mux) {

		//apply compression
		router.Use(middleware.DefaultCompress)
		router.Use(middleware.Logger)

		//content security policy
		csp := map[string][]string{
			"default-src": {"'self'", "data:", "'unsafe-inline'", "*.uservoice.com"},
			"script-src": {
				"'self'",
				"'unsafe-inline'",
				"'unsafe-eval'",
				"status.reportportal.io",
				"www.google-analytics.com",
				"stats.g.doubleclick.net",
				"*.saucelabs.com",
				"*.epam.com",
				"*.uservoice.com",
				"*.rawgit.com",
			},
			"worker-src": {"'self'", "blob:"},
            "font-src": {"'self'", "data:", "fonts.googleapis.com", "fonts.gstatic.com", "*.rawgit.com"},
            "style-src-elem": {"'self'", "data:", "'unsafe-inline'", "*.googleapis.com", "*.rawgit.com"},
            "media-src": {"'self'", "*.saucelabs.com"},
			"img-src": {"*", "'self'", "data:", "blob:"},
			"object-src": {"'self'"},
		}

		//apply content security policies
		router.Use(func(next http.Handler) http.Handler {
			return secure.New(secure.Options{
				ContentTypeNosniff:    true,
				BrowserXssFilter:      true,
				ContentSecurityPolicy: buildCSP(csp),
				STSSeconds:            315360000,
				STSIncludeSubdomains:  true,
				STSPreload:            true,
			}).Handler(next)
		})

		err := os.Chdir(rpConf.StaticsPath)
		if nil != err {
			log.Fatalf("Dir %s not found", rpConf.StaticsPath)
		}

		router.Handle("/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			//trim query params
			ext := filepath.Ext(trimQuery(r.URL.String(), "?"))

			// never cache html
			if "/" == r.URL.String() || ".html" == ext {
				w.Header().Add("Cache-Control", "no-cache")
			}

			http.FileServer(http.Dir(rpConf.StaticsPath)).ServeHTTP(&redirectingRW{ResponseWriter: w, Request: r}, r)
		}))

	})

	srv.StartServer()

}

func trimQuery(s string, sep string) string {
	sepIndex := strings.Index(s, sep)
	if -1 != sepIndex {
		return s[:sepIndex]
	}
	return s
}

func buildCSP(csp map[string][]string) string {
	var instr []string
	for k, v := range csp {
		instr = append(instr, k+" "+strings.Join(v, " "))
	}
	return strings.Join(instr, "; ")

}

type redirectingRW struct {
	*http.Request
	http.ResponseWriter
	ignore bool
}

func (hrw *redirectingRW) Header() http.Header {
	return hrw.ResponseWriter.Header()
}

func (hrw *redirectingRW) WriteHeader(status int) {
	if status == 404 {
		hrw.ignore = true
		http.Redirect(hrw.ResponseWriter, hrw.Request, "/ui/#notfound", http.StatusTemporaryRedirect)
	} else {
		hrw.ResponseWriter.WriteHeader(status)
	}

}

func (hrw *redirectingRW) Write(p []byte) (int, error) {
	if hrw.ignore {
		return len(p), nil
	}
	return hrw.ResponseWriter.Write(p)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"strconv"
	"time"

	"github.com/annaddicks/docx"
)

func main() {
	now := time.Now()
	nt := nextTuesday(now)

	fmt.Println("Generating Agenda for", agendaMonthDayYear(nt))
	createDoc(nt)
}

func createDoc(t time.Time) {
	r, err := docx.ReadDocxFile("./Agenda.docx")
	if err != nil {
		panic(err)
	}

	prettyPrintDate := agendaMonthDayYear(t)
	dateWithPeriods := formatDate(t, formatPeriods)
	roles := GetRoles(formatDate(t, formatSlashes))

	docx1 := r.Editable()
	fileName := "./" + dateWithPeriods + ".docx"

	docx1.ReplaceHeader("Date", prettyPrintDate)
	docx1.Replace("president", roles.BoardMembers.President, -1)
	docx1.Replace("vpe", roles.BoardMembers.Vpe, -1)
	docx1.Replace("vpm", roles.BoardMembers.Vpm, -1)
	docx1.Replace("vppr", roles.BoardMembers.Vppr, -1)
	docx1.Replace("secretary", roles.BoardMembers.Secretary, -1)
	docx1.Replace("treasurer", roles.BoardMembers.Treasurer, -1)
	docx1.Replace("saa", roles.BoardMembers.Saa, -1)
	docx1.Replace("jokeMaster", roles.JokeMaster, -1)
	docx1.Replace("toastmasterOfDay", roles.Toastmaster, -1)
	docx1.Replace("generalEval", roles.Ge, -1)
	docx1.Replace("timer", roles.Timer, -1)
	docx1.Replace("ah-counter", roles.AhCounter, -1)
	docx1.Replace("grammarian", roles.Grammarian, -1)

	var nextTime time.Time
	var pastSpeechTime int
	var printString string
	for i := 0; i < 4; i++ {
		speechOrder := i + 1
		speaker := roles.Speakers[i]

		docx1.Replace("evaluator"+strconv.Itoa(speechOrder), speaker.Evaluator, -1)
		docx1.Replace("speaker"+strconv.Itoa(speechOrder)+"FirstLastName", speaker.Name, -1)
		docx1.Replace("firstName"+strconv.Itoa(speechOrder), speaker.firstName(), -1)
		docx1.Replace("speaker"+strconv.Itoa(speechOrder)+"Manual", speaker.Speech.manualName, -1)
		docx1.Replace("speaker"+strconv.Itoa(speechOrder)+"Speech", speaker.Speech.name, -1)

		//Replace speech times for the second - fourth speaker
		if speechOrder == 1 {
			curTime := time.Date(2017, time.January, 1, 7, 14, 0, 0, time.UTC)
			nextTime, _ = prettyPrintTime(curTime, 0)
			pastSpeechTime = speaker.Speech.max + 1

		} else {
			nextTime, printString = prettyPrintTime(nextTime, pastSpeechTime)
			docx1.Replace("e"+strconv.Itoa(speechOrder)+"t"+strconv.Itoa(speechOrder), printString, 1)

			nextTime, printString = prettyPrintTime(nextTime, +1)
			docx1.Replace("s"+strconv.Itoa(speechOrder)+"t"+strconv.Itoa(speechOrder), printString, 1)
			pastSpeechTime = speaker.Speech.max + 1
		}
	}
	docx1.Replace("tTMaster", roles.TableTopicsMaster, -1)
	_, printString = prettyPrintTime(nextTime, pastSpeechTime)
	docx1.Replace("ttmt", printString, 1)

	//Replace the next 4 weeks on the agenda.
	for i := range roles.FutureWeeks {
		nextWeek := roles.FutureWeeks[i]

		for j := range nextWeek {
			docx1.Replace("w"+strconv.Itoa(i)+"_"+strconv.Itoa(j), nextWeek[j], 1)
		}
	}

	docx1.WriteToFile(fileName)
	r.Close()
}
<commit_msg>use range in the loop<commit_after>package main

import (
	"fmt"
	"strconv"
	"time"

	"github.com/annaddicks/docx"
)

func main() {
	now := time.Now()
	nt := nextTuesday(now)

	fmt.Println("Generating Agenda for", agendaMonthDayYear(nt))
	createDoc(nt)
}

func createDoc(t time.Time) {
	r, err := docx.ReadDocxFile("./Agenda.docx")
	if err != nil {
		panic(err)
	}

	prettyPrintDate := agendaMonthDayYear(t)
	dateWithPeriods := formatDate(t, formatPeriods)
	roles := GetRoles(formatDate(t, formatSlashes))

	docx1 := r.Editable()
	fileName := "./" + dateWithPeriods + ".docx"

	docx1.ReplaceHeader("Date", prettyPrintDate)
	docx1.Replace("president", roles.BoardMembers.President, -1)
	docx1.Replace("vpe", roles.BoardMembers.Vpe, -1)
	docx1.Replace("vpm", roles.BoardMembers.Vpm, -1)
	docx1.Replace("vppr", roles.BoardMembers.Vppr, -1)
	docx1.Replace("secretary", roles.BoardMembers.Secretary, -1)
	docx1.Replace("treasurer", roles.BoardMembers.Treasurer, -1)
	docx1.Replace("saa", roles.BoardMembers.Saa, -1)
	docx1.Replace("jokeMaster", roles.JokeMaster, -1)
	docx1.Replace("toastmasterOfDay", roles.Toastmaster, -1)
	docx1.Replace("generalEval", roles.Ge, -1)
	docx1.Replace("timer", roles.Timer, -1)
	docx1.Replace("ah-counter", roles.AhCounter, -1)
	docx1.Replace("grammarian", roles.Grammarian, -1)

	var nextTime time.Time
	var pastSpeechTime int
	var printString string
	for i := range roles.Speakers {
		speechOrder := i + 1
		speaker := roles.Speakers[i]

		docx1.Replace("evaluator"+strconv.Itoa(speechOrder), speaker.Evaluator, -1)
		docx1.Replace("speaker"+strconv.Itoa(speechOrder)+"FirstLastName", speaker.Name, -1)
		docx1.Replace("firstName"+strconv.Itoa(speechOrder), speaker.firstName(), -1)
		docx1.Replace("speaker"+strconv.Itoa(speechOrder)+"Manual", speaker.Speech.manualName, -1)
		docx1.Replace("speaker"+strconv.Itoa(speechOrder)+"Speech", speaker.Speech.name, -1)

		//Replace speech times for the second - fourth speaker
		if speechOrder == 1 {
			curTime := time.Date(2017, time.January, 1, 7, 14, 0, 0, time.UTC)
			nextTime, _ = prettyPrintTime(curTime, 0)
			pastSpeechTime = speaker.Speech.max + 1

		} else {
			nextTime, printString = prettyPrintTime(nextTime, pastSpeechTime)
			docx1.Replace("e"+strconv.Itoa(speechOrder)+"t"+strconv.Itoa(speechOrder), printString, 1)

			nextTime, printString = prettyPrintTime(nextTime, +1)
			docx1.Replace("s"+strconv.Itoa(speechOrder)+"t"+strconv.Itoa(speechOrder), printString, 1)
			pastSpeechTime = speaker.Speech.max + 1
		}
	}
	docx1.Replace("tTMaster", roles.TableTopicsMaster, -1)
	_, printString = prettyPrintTime(nextTime, pastSpeechTime)
	docx1.Replace("ttmt", printString, 1)

	//Replace the next 4 weeks on the agenda.
	for i := range roles.FutureWeeks {
		nextWeek := roles.FutureWeeks[i]

		for j := range nextWeek {
			docx1.Replace("w"+strconv.Itoa(i)+"_"+strconv.Itoa(j), nextWeek[j], 1)
		}
	}

	docx1.WriteToFile(fileName)
	r.Close()
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/victorystick/subfix/subtitles"
	"io/ioutil"
	"os"
	"time"
)

var (
	outfile string
)

// usage:
// subfix file delay
func main() {
	flag.StringVar(&outfile, "outfile", "", "Name ouf the output file.")

	flag.Parse()

	if flag.NArg() < 1 || flag.NArg() > 2 {
		printUsage()
		os.Exit(0)
	}

	filename := flag.Arg(0)

	if outfile == "" {
		outfile = filename
	}

	if flag.NArg() == 1 {
		validateSubtitles(filename)

		fmt.Println(filename + " was successfully parsed.")
	} else {
		ext, err := subtitles.Extension(outfile)

		die(err)

		shift, err := time.ParseDuration(flag.Arg(1))

		die(err)

		subs := shiftSubtitles(filename, shift)

		text, err := subs.As(ext)

		die(err)

		err = ioutil.WriteFile(outfile, []byte(text), 0666)

		die(err)
	}
}

func validateSubtitles(filename string) {
	_, err := subtitles.ReadFile(filename)

	die(err)
}

func shiftSubtitles(filename string, shift time.Duration) *subtitles.Subtitles {
	subs, err := subtitles.ReadFile(filename)

	die(err)

	subs.Shift(shift)

	return subs
}

func die(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func printUsage() {
	fmt.Println("subfix filename delay")
	fmt.Println("\tsupported filetypes:   srt")
	fmt.Println("\texample delays:        4.3s 1200ms")
}
<commit_msg>Enabled convertion from one format to another<commit_after>package main

import (
	"flag"
	"fmt"
	"github.com/victorystick/subfix/subtitles"
	"io/ioutil"
	"os"
	"time"
)

var (
	outfile string
)

// usage:
// subfix file delay
func main() {
	flag.StringVar(&outfile, "outfile", "", "Name ouf the output file.")

	flag.Parse()

	if flag.NArg() < 1 || flag.NArg() > 2 {
		printUsage()
		os.Exit(0)
	}

	filename := flag.Arg(0)

	if outfile == "" {
		outfile = filename
	}

	if flag.NArg() == 1 {
		subs, err := subtitles.ReadFile(filename)

		die(err)

		if outfile != filename {
			ext, err := subtitles.Extension(outfile)

			die(err)

			text, err := subs.As(ext)

			die(err)

			err = ioutil.WriteFile(outfile, []byte(text), 0666)

			die(err)
		} else {
			fmt.Println(filename + " was successfully parsed.")
		}
	} else {
		ext, err := subtitles.Extension(outfile)

		die(err)

		shift, err := time.ParseDuration(flag.Arg(1))

		die(err)

		subs := shiftSubtitles(filename, shift)

		text, err := subs.As(ext)

		die(err)

		err = ioutil.WriteFile(outfile, []byte(text), 0666)

		die(err)
	}
}

func shiftSubtitles(filename string, shift time.Duration) *subtitles.Subtitles {
	subs, err := subtitles.ReadFile(filename)

	die(err)

	subs.Shift(shift)

	return subs
}

func die(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func printUsage() {
	fmt.Println("subfix filename delay")
	fmt.Println("\tsupported filetypes:   srt")
	fmt.Println("\texample delays:        4.3s 1200ms")
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"os"

	"github.com/buildkite/elastic-ci-stack-s3-secrets-hooks/s3"
	"github.com/buildkite/elastic-ci-stack-s3-secrets-hooks/secrets"
	"github.com/buildkite/elastic-ci-stack-s3-secrets-hooks/sshagent"
)

const (
	envBucket     = "BUILDKITE_PLUGIN_S3_SECRETS_BUCKET"
	envPrefix     = "BUILDKITE_PLUGIN_S3_SECRETS_BUCKET_PREFIX"
	envPipeline   = "BUILDKITE_PIPELINE_SLUG"
	envRepo       = "BUILDKITE_REPO"
	envCredHelper = "BUILDKITE_PLUGIN_S3_SECRETS_CREDHELPER"

	envDefaultRegion = "AWS_DEFAULT_REGION"
	defaultRegion    = "us-east-1"
)

func main() {
	log := log.New(os.Stderr, "[secrets] ", log.Lmsgprefix)
	if err := mainWithError(log); err != nil {
		log.Fatalf("fatal error: %v", err)
	}
}

func mainWithError(log *log.Logger) error {
	bucket := os.Getenv(envBucket)
	if bucket == "" {
		return nil
	}

	prefix := os.Getenv(envPrefix)
	if prefix == "" {
		prefix = os.Getenv(envPipeline)
	}
	if prefix == "" {
		return fmt.Errorf("%s or %s required", envPrefix, envPipeline)
	}

	region := os.Getenv(envDefaultRegion)
	if region == "" {
		region = defaultRegion
	}
	client, err := s3.New(region)
	if err != nil {
		return err
	}

	agent := &sshagent.Agent{}

	credHelper := os.Getenv(envCredHelper)
	if credHelper == "" {
		return fmt.Errorf("%s required", envCredHelper)
	}

	return secrets.Run(secrets.Config{
		Repo:                os.Getenv(envRepo),
		Bucket:              bucket,
		Prefix:              prefix,
		Client:              client,
		Logger:              log,
		SSHAgent:            agent,
		EnvSink:             os.Stdout,
		GitCredentialHelper: credHelper,
	})
}
<commit_msg>go: remove [secrets] log prefix; messes with Buildkite log headers.<commit_after>package main

import (
	"fmt"
	"log"
	"os"

	"github.com/buildkite/elastic-ci-stack-s3-secrets-hooks/s3"
	"github.com/buildkite/elastic-ci-stack-s3-secrets-hooks/secrets"
	"github.com/buildkite/elastic-ci-stack-s3-secrets-hooks/sshagent"
)

const (
	envBucket     = "BUILDKITE_PLUGIN_S3_SECRETS_BUCKET"
	envPrefix     = "BUILDKITE_PLUGIN_S3_SECRETS_BUCKET_PREFIX"
	envPipeline   = "BUILDKITE_PIPELINE_SLUG"
	envRepo       = "BUILDKITE_REPO"
	envCredHelper = "BUILDKITE_PLUGIN_S3_SECRETS_CREDHELPER"

	envDefaultRegion = "AWS_DEFAULT_REGION"
	defaultRegion    = "us-east-1"
)

func main() {
	log := log.New(os.Stderr, "", log.Lmsgprefix)
	if err := mainWithError(log); err != nil {
		log.Fatalf("fatal error: %v", err)
	}
}

func mainWithError(log *log.Logger) error {
	bucket := os.Getenv(envBucket)
	if bucket == "" {
		return nil
	}

	prefix := os.Getenv(envPrefix)
	if prefix == "" {
		prefix = os.Getenv(envPipeline)
	}
	if prefix == "" {
		return fmt.Errorf("%s or %s required", envPrefix, envPipeline)
	}

	region := os.Getenv(envDefaultRegion)
	if region == "" {
		region = defaultRegion
	}
	client, err := s3.New(region)
	if err != nil {
		return err
	}

	agent := &sshagent.Agent{}

	credHelper := os.Getenv(envCredHelper)
	if credHelper == "" {
		return fmt.Errorf("%s required", envCredHelper)
	}

	return secrets.Run(secrets.Config{
		Repo:                os.Getenv(envRepo),
		Bucket:              bucket,
		Prefix:              prefix,
		Client:              client,
		Logger:              log,
		SSHAgent:            agent,
		EnvSink:             os.Stdout,
		GitCredentialHelper: credHelper,
	})
}
<|endoftext|>


<commit_before>package main

import (
    "github.com/coreos/go-etcd/etcd"
    "runtime"
    "os/signal"
    "os"
    "strings"
    "log"
    "flag"
    "time"
)

var (
    logger = log.New(os.Stdout, "[discodns] ", log.Ldate|log.Ltime)
)

func main() {

    var addr = flag.String("listen", "0.0.0.0", "Listen IP address")
    var port = flag.Int("port", 53, "Port to listen on")
    var hosts = flag.String("etcd", "0.0.0.0:4001", "List of etcd hosts (comma separated)")
    var nameservers = flag.String("ns", "8.8.8.8:53", "Fallback nameservers (comma separated)")
    var timeout = flag.String("ns-timeout", "5s", "Default nameserver timeout")
    var domain = flag.String("domain", "local", "Constrain discodns to a domain")
    flag.Parse()

    // Parse the list of nameservers
    ns := strings.Split(*nameservers, ",")

    // Parse the timeout string
    nsTimeout, err := time.ParseDuration(*timeout)
    if err != nil {
        logger.Fatalf("Failed to parse duration '%s'", timeout)
    }

    // Cleanup the domain
    root_domain := strings.Trim(*domain, ".") + "."

    // Connect to ETCD (wait for a connection)
    etcd := etcd.NewClient(strings.Split(*hosts, ","))

    if !etcd.SyncCluster() {
        logger.Fatalf("Failed to connect to etcd cluster at launch time")
    }

    // Start up the DNS resolver server
    server := &Server{
        addr: *addr,
        port: *port,
        etcd: etcd,
        rTimeout: nsTimeout,
        wTimeout: nsTimeout,
        domain: root_domain,
        ns: ns}

    server.Run()

    logger.Printf("Listening on %s:%d\n", *addr, *port)

    sig := make(chan os.Signal)
    signal.Notify(sig, os.Interrupt)

forever:
    for {
        select {
        case <-sig:
            logger.Printf("Bye bye :(\n")
            break forever
        }
    }
}

func init() {
    runtime.GOMAXPROCS(runtime.NumCPU())
}
<commit_msg>Reduce the default nameserver timeout<commit_after>package main

import (
    "github.com/coreos/go-etcd/etcd"
    "runtime"
    "os/signal"
    "os"
    "strings"
    "log"
    "flag"
    "time"
)

var (
    logger = log.New(os.Stdout, "[discodns] ", log.Ldate|log.Ltime)
)

func main() {

    var addr = flag.String("listen", "0.0.0.0", "Listen IP address")
    var port = flag.Int("port", 53, "Port to listen on")
    var hosts = flag.String("etcd", "0.0.0.0:4001", "List of etcd hosts (comma separated)")
    var nameservers = flag.String("ns", "8.8.8.8:53", "Fallback nameservers (comma separated)")
    var timeout = flag.String("ns-timeout", "1s", "Default nameserver timeout")
    var domain = flag.String("domain", "local", "Constrain discodns to a domain")
    flag.Parse()

    // Parse the list of nameservers
    ns := strings.Split(*nameservers, ",")

    // Parse the timeout string
    nsTimeout, err := time.ParseDuration(*timeout)
    if err != nil {
        logger.Fatalf("Failed to parse duration '%s'", timeout)
    }

    // Cleanup the domain
    root_domain := strings.Trim(*domain, ".") + "."

    // Connect to ETCD (wait for a connection)
    etcd := etcd.NewClient(strings.Split(*hosts, ","))

    if !etcd.SyncCluster() {
        logger.Fatalf("Failed to connect to etcd cluster at launch time")
    }

    // Start up the DNS resolver server
    server := &Server{
        addr: *addr,
        port: *port,
        etcd: etcd,
        rTimeout: nsTimeout,
        wTimeout: nsTimeout,
        domain: root_domain,
        ns: ns}

    server.Run()

    logger.Printf("Listening on %s:%d\n", *addr, *port)

    sig := make(chan os.Signal)
    signal.Notify(sig, os.Interrupt)

forever:
    for {
        select {
        case <-sig:
            logger.Printf("Bye bye :(\n")
            break forever
        }
    }
}

func init() {
    runtime.GOMAXPROCS(runtime.NumCPU())
}
<|endoftext|>


<commit_before>package main

import (
	// "encoding/json"
	"log"
)

// TODO: whole twitter post?
type event struct {
	EventName     string `json:"EventName"`
	VenueName     string `json:"VenueName"`
	VenueLocation string `json:"VenueLocation"`
	StartTime     string `json:"StartTime"`
	EndTime       string `json:"EndTime"`
	Description   string `json:"Description"`
}

func main() {
	log.Println("Starting up easy-megaphone")

	setup()

	readFromJSON()

	sendToCalagator()
}

func setup() {
	// envconfig bits for various integration, such as Meetups API
}

func readFromJSON() {
	// read from JSON input file
}

func sendToCalagator() {
	log.Println("Sending to calagator...")
	// Totally sends to calagator
}
<commit_msg>Fleshes out basic structure more, ready for some implementation.<commit_after>package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
)

// TODO: whole twitter post?
type event struct {
	EventName     string `json:"EventName"`
	VenueName     string `json:"VenueName"`
	VenueLocation string `json:"VenueLocation"`
	StartTime     string `json:"StartTime"`
	EndTime       string `json:"EndTime"`
	Description   string `json:"Description"`
}

func main() {
	log.Println("Starting up easy-megaphone")

	setup()

	// TODO: take in a flag with a file to post.
	eventJSON, _ := readFileContents("sample-event.json")

	eventEntry := readFromJSON(eventJSON)

	// These can be refactored into a single function that calls them all
	sendToCalagator(eventEntry)
	sendToMeetup(eventEntry)
	sendToAgilePDXWebsite(eventEntry)
	sendToTwitter(eventEntry)
}

func setup() {
	// envconfig bits for various integration, such as Meetups API
}

func readFileContents(file string) ([]byte, error) {
	fileAsBytes, err := ioutil.ReadFile(file)

	if err != nil {
		log.Fatalln("Couldn't open ", file)
	}

	return fileAsBytes, nil
}

func readFromJSON(eventJSON []byte) event {
	var eventEntry event
	err := json.Unmarshal([]byte(eventJSON), &eventEntry)

	if err != nil {
		log.Fatal("Couldn't parse JSON file.")
	}
	return eventEntry
}

func sendToCalagator(eventEntry event) {
	log.Println("Totally sending to calagator...")
	bleh, _ := json.Marshal(eventEntry)
	log.Println(string(bleh))
}

func sendToMeetup(eventEntry event) {
	log.Println("Totally sending to meetup...")
}

func sendToAgilePDXWebsite(eventEntry event) {
	log.Println("Totally sending to agilepdx website...")
}

func sendToTwitter(eventEntry event) {
	log.Println("Totally sending to twitter...")
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strconv"
	"strings"
)

type Builtin struct {
	Run func(args []string)
}

var BUILTINS = map[string]*Builtin{
	"cd": &Builtin{func(args []string) {
		os.Chdir(args[0])
	}},
	"exit": &Builtin{func(args []string) {
		var code int
		if len(args) == 1 {
			code, _ = strconv.Atoi(args[0])
		}
		os.Exit(code)
	}},
	"exec": &Builtin{func(args []string) {
		spawnProgram(args[0], args[1:])
	}},
	"set": &Builtin{func(args []string) {
		for _, arg := range args {
			keyValuePair := strings.Split(arg, "=")
			if len(keyValuePair) == 2 {
				os.Setenv(keyValuePair[0], keyValuePair[1])
			}
		}
	}},
}

func main() {
	os.Setenv("PROMPT", "->")
	prompt()
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		name, args := parseCmd(scanner.Text())
		if isBuiltin(name) {
			callBuiltin(name, args)
		} else {
			spawnProgram(name, args)
		}
		prompt()
	}

	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "Reading standard input:", err)
	}
}

func prompt() {
	fmt.Fprintf(os.Stdout, "%s ", os.Getenv("PROMPT"))
}

func parseCmd(text string) (name string, args []string) {
	regexpBySpace := regexp.MustCompile("\\s+")
	cmd := regexpBySpace.Split(text, -1)

	name = cmd[0]
	// expand environment variables
	// somehow os/exec.Command.Run() doesn't expand automatically
	envVarRegexp := regexp.MustCompile("^\\$(.+)$")
	for _, arg := range cmd[1:] {
		if envVarRegexp.MatchString(arg) {
			match := envVarRegexp.FindStringSubmatch(arg)
			arg = os.Getenv(match[1])
		}

		args = append(args, arg)
	}

	return
}

func isBuiltin(name string) bool {
	_, ok := BUILTINS[name]

	return ok
}

func callBuiltin(name string, args []string) {
	builtin, _ := BUILTINS[name]
	builtin.Run(args)
}

func spawnProgram(name string, args []string) {
	cmdFullPath, err := exec.LookPath(name)
	if err != nil {
		fmt.Fprintf(os.Stderr, "osh: command not found: %s", name)
	}

	var stdout, stderr bytes.Buffer
	c := exec.Command(cmdFullPath, args...)
	c.Env = os.Environ()
	c.Stdin = os.Stdin
	c.Stdout = &stdout
	c.Stderr = &stderr

	err = c.Run()
	if err != nil {
		fmt.Fprintln(os.Stderr, stderr.String())
	}

	fmt.Fprint(os.Stdout, stdout.String())
}
<commit_msg>Redirect pipe<commit_after>package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"os/exec"
	"regexp"
	"strconv"
	"strings"
)

type Builtin struct {
	Run func(args []string)
}

var BUILTINS = map[string]*Builtin{
	"cd": &Builtin{func(args []string) {
		os.Chdir(args[0])
	}},
	"exit": &Builtin{func(args []string) {
		var code int
		if len(args) == 1 {
			code, _ = strconv.Atoi(args[0])
		}
		os.Exit(code)
	}},
	"exec": &Builtin{func(args []string) {
		spawnProgram(args[0], args[1:], os.Stdin, os.Stdout)
	}},
	"set": &Builtin{func(args []string) {
		for _, arg := range args {
			keyValuePair := strings.Split(arg, "=")
			if len(keyValuePair) == 2 {
				os.Setenv(keyValuePair[0], keyValuePair[1])
			}
		}
	}},
}

func main() {
	os.Setenv("PROMPT", "->")
	prompt()
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		commands := splitOnPipes(scanner.Text())
		var placeHolderIn io.ReadCloser = os.Stdin
		var placeHolderOut io.WriteCloser = os.Stdout
		var pipeReader *io.PipeReader

		for i, command := range commands {
			name, args := parseCommand(command)
			if isBuiltin(name) {
				callBuiltin(name, args)
			} else {
				if i+1 < len(commands) {
					pipeReader, placeHolderOut = io.Pipe()
				} else {
					placeHolderOut = os.Stdout
				}

				spawnProgram(name, args, placeHolderOut, placeHolderIn)

				if placeHolderOut != os.Stdout {
					placeHolderOut.Close()
				}

				if placeHolderIn != os.Stdin {
					placeHolderIn.Close()
				}

				placeHolderIn = pipeReader
			}
		}
		prompt()
	}

	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "Reading standard input:", err)
	}
}

func prompt() {
	fmt.Fprintf(os.Stdout, "%s ", os.Getenv("PROMPT"))
}

func splitOnPipes(line string) (commands []string) {
	pipesRegexp := regexp.MustCompile("([^\"'|]+)|[\"']([^\"']+)[\"']")
	if pipesRegexp.MatchString(line) {
		commands = pipesRegexp.FindAllString(line, -1)
	} else {
		commands = append(commands, line)
	}

	for i, command := range commands {
		commands[i] = strings.TrimSpace(command)
	}

	return
}

func parseCommand(line string) (name string, args []string) {
	regexpBySpace := regexp.MustCompile("\\s+")
	cmd := regexpBySpace.Split(line, -1)

	name = cmd[0]
	// expand environment variables
	// somehow os/exec.Command.Run() doesn't expand automatically
	envVarRegexp := regexp.MustCompile("^\\$(.+)$")
	for _, arg := range cmd[1:] {
		if envVarRegexp.MatchString(arg) {
			match := envVarRegexp.FindStringSubmatch(arg)
			arg = os.Getenv(match[1])
		}

		args = append(args, arg)
	}

	return
}

func isBuiltin(name string) bool {
	_, ok := BUILTINS[name]

	return ok
}

func callBuiltin(name string, args []string) {
	builtin, _ := BUILTINS[name]
	builtin.Run(args)
}

func spawnProgram(name string, args []string, placeHolderOut io.WriteCloser, placeHolderIn io.ReadCloser) {
	cmdFullPath, err := exec.LookPath(name)
	if err != nil {
		fmt.Fprintf(os.Stderr, "osh: command not found: %s", name)
	}

	c := exec.Command(cmdFullPath, args...)
	c.Env = os.Environ()

	c.Stdin = placeHolderIn
	c.Stdout = placeHolderOut
	c.Stderr = c.Stdout

	err = c.Run()
	if err != nil {
		//fmt.Fprintln(os.Stderr, stderr.String())
		panic(err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"path"
	"runtime"

	"gopkg.in/jackc/pgx.v2"

	"github.com/golang/groupcache"
	"github.com/gorilla/mux"
	"github.com/jessevdk/go-flags"

	"github.com/LeKovr/dbrpc/workman"
	"github.com/LeKovr/go-base/logger"

	_ "expvar"
	_ "net/http/pprof"
)

// -----------------------------------------------------------------------------

// Flags defines local application flags
type Flags struct {
	Addr       string `long:"http_addr" default:"localhost:8081"  description:"Http listen address"`
	CacheGroup string `long:"cache_group" default:"DBRPC"  description:"Cache group name"`
	CacheSize  int64  `long:"cache_size" default:"67108864"  description:"Cache size in bytes"` // 64<<20
	Version    bool   `long:"version" description:"Show version and exit"`
	Connect    string `long:"db_connect" default:"user:pass@localhost/userdb?sslmode=disable" description:"Database connect string"`
}

// AplFlags defines applied logic flags
type AplFlags struct {
	Prefix     string   `long:"url_prefix" default:"/api/"  description:"Http request prefix"`
	Schema     string   `long:"db_schema" default:"public" description:"Database functions schema name or comma delimited list"`
	ArgDefFunc string   `long:"db_argdef" default:"pg_func_args" description:"Argument definition function"`
	Hosts      []string `long:"http_origin" description:"Allowed http origin(s)"`
}

// Config defines all of application flags
type Config struct {
	Flags
	apl AplFlags
	log logger.Flags
	wm  workman.Flags
}

// -----------------------------------------------------------------------------

func main() {

	var cfg Config
	log, db, _ := setUp(&cfg)
	defer log.Close()
	defer db.Close()

	Program := path.Base(os.Args[0])
	log.Infof("%s v %s. DataBase RPC service", Program, Version)
	log.Println("Copyright (C) 2016, Alexey Kovrizhkin <ak@elfire.ru>")

	mux1, wm := Handlers(&cfg, log, db)
	wm.Run()
	defer wm.Stop()

	/*
	   peers := groupcache.NewHTTPPool("http://localhost:" + *port)
	   http.ListenAndServe("127.0.0.1:"+*port, http.HandlerFunc(peers.ServeHTTP))
	*/

	runServer(cfg, log, mux1)

	log.Println("Server stopped")
	os.Exit(0)
}

// -----------------------------------------------------------------------------

// Handlers used to prepare and http handlers
func Handlers(cfg *Config, log *logger.Log, db *pgx.Conn) (*mux.Router, *workman.WorkMan) {

	cache := groupcache.NewGroup(
		cfg.CacheGroup,
		cfg.CacheSize,
		groupcache.GetterFunc(dbFetcher(&cfg.apl, log, db)),
	)
	log.Debugf("Cache group %s with size: %d", cfg.CacheGroup, cfg.CacheSize)

	wm, err := workman.New(
		workman.WorkerFunc(cacheFetcher(log, cache)),
		workman.Config(&cfg.wm),
		workman.Logger(log),
	)
	panicIfError(err)

	r := mux.NewRouter()
	r.PathPrefix(cfg.apl.Prefix).Handler(httpHandler(&cfg.apl, log, wm.JobQueue))

	return r, wm
}

// -----------------------------------------------------------------------------

func makeConfig(cfg *Config) *flags.Parser {
	p := flags.NewParser(nil, flags.Default)
	_, err := p.AddGroup("Application Options", "", cfg)
	panicIfError(err) // check Flags parse error

	_, err = p.AddGroup("Applied logic Options", "", &cfg.apl)
	panicIfError(err) // check Flags parse error

	_, err = p.AddGroup("Logging Options", "", &cfg.log)
	panicIfError(err) // check Flags parse error

	_, err = p.AddGroup("WorkerManager Options", "", &cfg.wm)
	panicIfError(err) // check Flags parse error
	return p
}

func setUp(cfg *Config) (log *logger.Log, db *pgx.Conn, err error) {

	p := makeConfig(cfg)

	_, err = p.Parse()
	if err != nil {
		os.Exit(1) // error message written already
	}
	if cfg.Version {
		// show version & exit
		fmt.Printf("%s\n%s\n%s", Version, Build, Commit)
		os.Exit(0)
	}

	// use all CPU cores for maximum performance
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Create a new instance of the logger
	log, err = logger.New(logger.Dest(cfg.log.Dest), logger.Level(cfg.log.Level))
	panicIfError(err) // check Flags parse error

	// Setup database
	c, err := pgx.ParseURI("postgres://" + cfg.Connect)
	panicIfError(err) // check Flags parse error
	db, err = pgx.Connect(c)
	panicIfError(err) // check Flags parse error

	if cfg.apl.Schema != "public" {
		_, err = db.Exec("set search_path = " + cfg.apl.Schema + ", public")
		panicIfError(err)
	}
	return
}

// -----------------------------------------------------------------------------

func panicIfError(err error) {
	if err != nil {
		panic(err)
	}
}
<commit_msg>fix: do not add public always<commit_after>package main

import (
	"fmt"
	"os"
	"path"
	"runtime"

	"gopkg.in/jackc/pgx.v2"

	"github.com/golang/groupcache"
	"github.com/gorilla/mux"
	"github.com/jessevdk/go-flags"

	"github.com/LeKovr/dbrpc/workman"
	"github.com/LeKovr/go-base/logger"

	_ "expvar"
	_ "net/http/pprof"
)

// -----------------------------------------------------------------------------

// Flags defines local application flags
type Flags struct {
	Addr       string `long:"http_addr" default:"localhost:8081"  description:"Http listen address"`
	CacheGroup string `long:"cache_group" default:"DBRPC"  description:"Cache group name"`
	CacheSize  int64  `long:"cache_size" default:"67108864"  description:"Cache size in bytes"` // 64<<20
	Version    bool   `long:"version" description:"Show version and exit"`
	Connect    string `long:"db_connect" default:"user:pass@localhost/userdb?sslmode=disable" description:"Database connect string"`
}

// AplFlags defines applied logic flags
type AplFlags struct {
	Prefix     string   `long:"url_prefix" default:"/api/"  description:"Http request prefix"`
	Schema     string   `long:"db_schema" default:"public" description:"Database functions schema name or comma delimited list"`
	ArgDefFunc string   `long:"db_argdef" default:"pg_func_args" description:"Argument definition function"`
	Hosts      []string `long:"http_origin" description:"Allowed http origin(s)"`
}

// Config defines all of application flags
type Config struct {
	Flags
	apl AplFlags
	log logger.Flags
	wm  workman.Flags
}

// -----------------------------------------------------------------------------

func main() {

	var cfg Config
	log, db, _ := setUp(&cfg)
	defer log.Close()
	defer db.Close()

	Program := path.Base(os.Args[0])
	log.Infof("%s v %s. DataBase RPC service", Program, Version)
	log.Println("Copyright (C) 2016, Alexey Kovrizhkin <ak@elfire.ru>")

	mux1, wm := Handlers(&cfg, log, db)
	wm.Run()
	defer wm.Stop()

	/*
	   peers := groupcache.NewHTTPPool("http://localhost:" + *port)
	   http.ListenAndServe("127.0.0.1:"+*port, http.HandlerFunc(peers.ServeHTTP))
	*/

	runServer(cfg, log, mux1)

	log.Println("Server stopped")
	os.Exit(0)
}

// -----------------------------------------------------------------------------

// Handlers used to prepare and http handlers
func Handlers(cfg *Config, log *logger.Log, db *pgx.Conn) (*mux.Router, *workman.WorkMan) {

	cache := groupcache.NewGroup(
		cfg.CacheGroup,
		cfg.CacheSize,
		groupcache.GetterFunc(dbFetcher(&cfg.apl, log, db)),
	)
	log.Debugf("Cache group %s with size: %d", cfg.CacheGroup, cfg.CacheSize)

	wm, err := workman.New(
		workman.WorkerFunc(cacheFetcher(log, cache)),
		workman.Config(&cfg.wm),
		workman.Logger(log),
	)
	panicIfError(err)

	r := mux.NewRouter()
	r.PathPrefix(cfg.apl.Prefix).Handler(httpHandler(&cfg.apl, log, wm.JobQueue))

	return r, wm
}

// -----------------------------------------------------------------------------

func makeConfig(cfg *Config) *flags.Parser {
	p := flags.NewParser(nil, flags.Default)
	_, err := p.AddGroup("Application Options", "", cfg)
	panicIfError(err) // check Flags parse error

	_, err = p.AddGroup("Applied logic Options", "", &cfg.apl)
	panicIfError(err) // check Flags parse error

	_, err = p.AddGroup("Logging Options", "", &cfg.log)
	panicIfError(err) // check Flags parse error

	_, err = p.AddGroup("WorkerManager Options", "", &cfg.wm)
	panicIfError(err) // check Flags parse error
	return p
}

func setUp(cfg *Config) (log *logger.Log, db *pgx.Conn, err error) {

	p := makeConfig(cfg)

	_, err = p.Parse()
	if err != nil {
		os.Exit(1) // error message written already
	}
	if cfg.Version {
		// show version & exit
		fmt.Printf("%s\n%s\n%s", Version, Build, Commit)
		os.Exit(0)
	}

	// use all CPU cores for maximum performance
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Create a new instance of the logger
	log, err = logger.New(logger.Dest(cfg.log.Dest), logger.Level(cfg.log.Level))
	panicIfError(err) // check Flags parse error

	// Setup database
	c, err := pgx.ParseURI("postgres://" + cfg.Connect)
	panicIfError(err) // check Flags parse error
	db, err = pgx.Connect(c)
	panicIfError(err) // check Flags parse error

	if cfg.apl.Schema != "public" {
		_, err = db.Exec("set search_path = " + cfg.apl.Schema)
		panicIfError(err)
	}
	return
}

// -----------------------------------------------------------------------------

func panicIfError(err error) {
	if err != nil {
		panic(err)
	}
}
<|endoftext|>


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

package processor

import (
	"context"

	commonpb "github.com/census-instrumentation/opencensus-proto/gen-go/agent/common/v1"
	"go.opencensus.io/stats"
	"go.opencensus.io/stats/view"
	"go.opencensus.io/tag"

	"go.opentelemetry.io/collector/config/configtelemetry"
	"go.opentelemetry.io/collector/consumer/pdata"
	"go.opentelemetry.io/collector/internal/collector/telemetry"
	"go.opentelemetry.io/collector/obsreport"
	"go.opentelemetry.io/collector/translator/conventions"
)

// Keys and stats for telemetry.
var (
	TagServiceNameKey, _   = tag.NewKey("service")
	TagProcessorNameKey, _ = tag.NewKey(obsreport.ProcessorKey)

	StatReceivedSpanCount = stats.Int64(
		"spans_received",
		"counts the number of spans received",
		stats.UnitDimensionless)
	StatDroppedSpanCount = stats.Int64(
		"spans_dropped",
		"counts the number of spans dropped",
		stats.UnitDimensionless)

	StatTraceBatchesDroppedCount = stats.Int64(
		"trace_batches_dropped",
		"counts the number of trace batches dropped",
		stats.UnitDimensionless)
)

// SpanCountStats represents span count stats grouped by service if DETAILED telemetry level is set,
// otherwise only overall span count is stored in serviceSpansCounts.
type SpanCountStats struct {
	serviceSpansCounts map[string]int
	allSpansCount      int
	isDetailed         bool
}

func NewSpanCountStats(td pdata.Traces) *SpanCountStats {
	scm := &SpanCountStats{
		allSpansCount: td.SpanCount(),
	}
	if serviceTagsEnabled() {
		scm.serviceSpansCounts = spanCountByResourceStringAttribute(td, conventions.AttributeServiceName)
		scm.isDetailed = true
	}
	return scm
}

func (scm *SpanCountStats) GetAllSpansCount() int {
	return scm.allSpansCount
}

// MetricTagKeys returns the metric tag keys according to the given telemetry level.
func MetricTagKeys(level configtelemetry.Level) []tag.Key {
	var tagKeys []tag.Key
	switch level {
	case configtelemetry.LevelDetailed:
		tagKeys = append(tagKeys, TagServiceNameKey)
		fallthrough
	case configtelemetry.LevelNormal, configtelemetry.LevelBasic:
		tagKeys = append(tagKeys, TagProcessorNameKey)
	default:
		return nil
	}

	return tagKeys
}

// MetricViews return the metrics views according to given telemetry level.
func MetricViews(level configtelemetry.Level) []*view.View {
	tagKeys := MetricTagKeys(level)
	if tagKeys == nil {
		return nil
	}

	// There are some metrics enabled, return the views.
	receivedBatchesView := &view.View{
		Name:        "batches_received",
		Measure:     StatReceivedSpanCount,
		Description: "The number of span batches received.",
		TagKeys:     tagKeys,
		Aggregation: view.Count(),
	}
	droppedBatchesView := &view.View{
		Measure:     StatTraceBatchesDroppedCount,
		Description: "The number of span batches dropped.",
		TagKeys:     tagKeys,
		Aggregation: view.Sum(),
	}
	receivedSpansView := &view.View{
		Name:        StatReceivedSpanCount.Name(),
		Measure:     StatReceivedSpanCount,
		Description: "The number of spans received.",
		TagKeys:     tagKeys,
		Aggregation: view.Sum(),
	}
	droppedSpansView := &view.View{
		Name:        StatDroppedSpanCount.Name(),
		Measure:     StatDroppedSpanCount,
		Description: "The number of spans dropped.",
		TagKeys:     tagKeys,
		Aggregation: view.Sum(),
	}

	legacyViews := []*view.View{
		receivedBatchesView,
		droppedBatchesView,
		receivedSpansView,
		droppedSpansView,
	}

	return obsreport.ProcessorMetricViews("", legacyViews)
}

// ServiceNameForNode gets the service name for a specified node.
func ServiceNameForNode(node *commonpb.Node) string {
	switch {
	case node == nil:
		return "<nil-batch-node>"
	case node.ServiceInfo == nil:
		return "<nil-service-info>"
	case node.ServiceInfo.Name == "":
		return "<empty-service-info-name>"
	default:
		return node.ServiceInfo.Name
	}
}

// RecordsSpanCountMetrics reports span count metrics for specified measure.
func RecordsSpanCountMetrics(ctx context.Context, scm *SpanCountStats, measure *stats.Int64Measure) {
	if scm.isDetailed {
		for serviceName, spanCount := range scm.serviceSpansCounts {
			statsTags := []tag.Mutator{tag.Insert(TagServiceNameKey, serviceName)}
			_ = stats.RecordWithTags(ctx, statsTags, measure.M(int64(spanCount)))
		}
		return
	}

	stats.Record(ctx, measure.M(int64(scm.allSpansCount)))
}

func serviceTagsEnabled() bool {
	level, err := telemetry.GetLevel()
	return err == nil && level == configtelemetry.LevelDetailed
}

// spanCountByResourceStringAttribute calculates the number of spans by resource specified by
// provided string attribute attrKey.
func spanCountByResourceStringAttribute(td pdata.Traces, attrKey string) map[string]int {
	spanCounts := make(map[string]int)

	rss := td.ResourceSpans()
	for i := 0; i < rss.Len(); i++ {
		rs := rss.At(i)
		if rs.IsNil() {
			continue
		}

		var attrStringVal string
		if attrVal, ok := rs.Resource().Attributes().Get(attrKey); ok {
			attrStringVal = attrVal.StringVal()
		}
		ilss := rs.InstrumentationLibrarySpans()
		for j := 0; j < ilss.Len(); j++ {
			ils := ilss.At(j)
			if ils.IsNil() {
				continue
			}
			spanCounts[attrStringVal] += ilss.At(j).Spans().Len()
		}
	}
	return spanCounts
}
<commit_msg>Remove unused public func ServiceNameForNode (#2120)<commit_after>// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package processor

import (
	"context"

	"go.opencensus.io/stats"
	"go.opencensus.io/stats/view"
	"go.opencensus.io/tag"

	"go.opentelemetry.io/collector/config/configtelemetry"
	"go.opentelemetry.io/collector/consumer/pdata"
	"go.opentelemetry.io/collector/internal/collector/telemetry"
	"go.opentelemetry.io/collector/obsreport"
	"go.opentelemetry.io/collector/translator/conventions"
)

// Keys and stats for telemetry.
var (
	TagServiceNameKey, _   = tag.NewKey("service")
	TagProcessorNameKey, _ = tag.NewKey(obsreport.ProcessorKey)

	StatReceivedSpanCount = stats.Int64(
		"spans_received",
		"counts the number of spans received",
		stats.UnitDimensionless)
	StatDroppedSpanCount = stats.Int64(
		"spans_dropped",
		"counts the number of spans dropped",
		stats.UnitDimensionless)

	StatTraceBatchesDroppedCount = stats.Int64(
		"trace_batches_dropped",
		"counts the number of trace batches dropped",
		stats.UnitDimensionless)
)

// SpanCountStats represents span count stats grouped by service if DETAILED telemetry level is set,
// otherwise only overall span count is stored in serviceSpansCounts.
type SpanCountStats struct {
	serviceSpansCounts map[string]int
	allSpansCount      int
	isDetailed         bool
}

func NewSpanCountStats(td pdata.Traces) *SpanCountStats {
	scm := &SpanCountStats{
		allSpansCount: td.SpanCount(),
	}
	if serviceTagsEnabled() {
		scm.serviceSpansCounts = spanCountByResourceStringAttribute(td, conventions.AttributeServiceName)
		scm.isDetailed = true
	}
	return scm
}

func (scm *SpanCountStats) GetAllSpansCount() int {
	return scm.allSpansCount
}

// MetricTagKeys returns the metric tag keys according to the given telemetry level.
func MetricTagKeys(level configtelemetry.Level) []tag.Key {
	var tagKeys []tag.Key
	switch level {
	case configtelemetry.LevelDetailed:
		tagKeys = append(tagKeys, TagServiceNameKey)
		fallthrough
	case configtelemetry.LevelNormal, configtelemetry.LevelBasic:
		tagKeys = append(tagKeys, TagProcessorNameKey)
	default:
		return nil
	}

	return tagKeys
}

// MetricViews return the metrics views according to given telemetry level.
func MetricViews(level configtelemetry.Level) []*view.View {
	tagKeys := MetricTagKeys(level)
	if tagKeys == nil {
		return nil
	}

	// There are some metrics enabled, return the views.
	receivedBatchesView := &view.View{
		Name:        "batches_received",
		Measure:     StatReceivedSpanCount,
		Description: "The number of span batches received.",
		TagKeys:     tagKeys,
		Aggregation: view.Count(),
	}
	droppedBatchesView := &view.View{
		Measure:     StatTraceBatchesDroppedCount,
		Description: "The number of span batches dropped.",
		TagKeys:     tagKeys,
		Aggregation: view.Sum(),
	}
	receivedSpansView := &view.View{
		Name:        StatReceivedSpanCount.Name(),
		Measure:     StatReceivedSpanCount,
		Description: "The number of spans received.",
		TagKeys:     tagKeys,
		Aggregation: view.Sum(),
	}
	droppedSpansView := &view.View{
		Name:        StatDroppedSpanCount.Name(),
		Measure:     StatDroppedSpanCount,
		Description: "The number of spans dropped.",
		TagKeys:     tagKeys,
		Aggregation: view.Sum(),
	}

	legacyViews := []*view.View{
		receivedBatchesView,
		droppedBatchesView,
		receivedSpansView,
		droppedSpansView,
	}

	return obsreport.ProcessorMetricViews("", legacyViews)
}

// RecordsSpanCountMetrics reports span count metrics for specified measure.
func RecordsSpanCountMetrics(ctx context.Context, scm *SpanCountStats, measure *stats.Int64Measure) {
	if scm.isDetailed {
		for serviceName, spanCount := range scm.serviceSpansCounts {
			statsTags := []tag.Mutator{tag.Insert(TagServiceNameKey, serviceName)}
			_ = stats.RecordWithTags(ctx, statsTags, measure.M(int64(spanCount)))
		}
		return
	}

	stats.Record(ctx, measure.M(int64(scm.allSpansCount)))
}

func serviceTagsEnabled() bool {
	level, err := telemetry.GetLevel()
	return err == nil && level == configtelemetry.LevelDetailed
}

// spanCountByResourceStringAttribute calculates the number of spans by resource specified by
// provided string attribute attrKey.
func spanCountByResourceStringAttribute(td pdata.Traces, attrKey string) map[string]int {
	spanCounts := make(map[string]int)

	rss := td.ResourceSpans()
	for i := 0; i < rss.Len(); i++ {
		rs := rss.At(i)
		if rs.IsNil() {
			continue
		}

		var attrStringVal string
		if attrVal, ok := rs.Resource().Attributes().Get(attrKey); ok {
			attrStringVal = attrVal.StringVal()
		}
		ilss := rs.InstrumentationLibrarySpans()
		for j := 0; j < ilss.Len(); j++ {
			ils := ilss.At(j)
			if ils.IsNil() {
				continue
			}
			spanCounts[attrStringVal] += ilss.At(j).Spans().Len()
		}
	}
	return spanCounts
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"flag"
	c "github.com/byxorna/collinsbot/collins"
	"github.com/nlopes/slack"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

var (
	cli struct {
		file    string
		token   string
		botname string
		debug   bool
	}
	settings   Settings
	api        *slack.Slack
	ws         *slack.SlackWS
	postParams slack.PostMessageParameters
	collins    *c.Client

	botIdentity *slack.AuthTestResponse

	// message handlers are functions that process a message event
	// similar to http route handlers. The first to return true stops processing
	messagehandlers = []Handler{
		Handler{"Help", HelpHandler},
		Handler{"YouAlive", YouAliveHandler},
		Handler{"AssetTag", AssetTagHandler},
		Handler{"AssetHostname", AssetHostnameHandler},
		Handler{"WTF", WTFHandler},
	}

	helpinfo = map[string]string{
		"help": "show this help output",
		"yt?":  "see if I am still alive",
		"mention any asset tag or hostname": "get a link to the asset",
	}
)

func init() {
	flag.StringVar(&cli.token, "token", "", "Slack API token")
	flag.StringVar(&cli.botname, "botname", "", "Bot name")
	flag.StringVar(&cli.file, "config", "", "File containing Slack API token")
	flag.BoolVar(&cli.debug, "debug", false, "Turn on Slack API debugging")
	flag.Parse()
}

func main() {
	if cli.file != "" {
		log.Printf("Loading config from %s\n", cli.file)
		f, err := os.Open(cli.file)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		err = json.NewDecoder(f).Decode(&settings)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Fatal("You need to pass a json file to -config")
	}

	// override whats in the settings with whats on the cli
	if cli.token != "" {
		log.Printf("Slack token passed via CLI: %s\n", cli.token)
		settings.Token = cli.token
	}
	if settings.Botname == "" || cli.botname != "" {
		settings.Botname = cli.botname
	}

	if settings.Token == "" {
		log.Fatal("You need to give me an API token!")
	}

	collins = c.New(settings.Collins.Username, settings.Collins.Password, settings.Collins.Host)

	// set up posting params
	postParams = slack.NewPostMessageParameters()
	postParams.Username = settings.Botname
	//postParams.LinkNames = 1
	// we will perform proper formatting per https://api.slack.com/docs/formatting, do make the server do no processing
	postParams.Parse = "none"

	api = slack.New(settings.Token)
	api.SetDebug(cli.debug)
	authresp, err := api.AuthTest()
	if err != nil {
		log.Fatal(err)
	}
	botIdentity = authresp
	log.Printf("Authed with Slack successfully as %s (%s)\n", botIdentity.User, botIdentity.UserId)

	chIncomingEvents := make(chan slack.SlackEvent)
	chOutgoingMessages := make(chan slack.OutgoingMessage)
	ws, err = api.StartRTM("", "https://www.tumblr.com")
	if err != nil {
		log.Fatal("Unable to start realtime messaging websocket: %s\n", err.Error())
	}

	// send incoming events into the chIncomingEvents channel
	// and record when we started listening for events so we can ignore those which happened earlier
	var socketEstablished = time.Now().Unix()
	go ws.HandleIncomingEvents(chIncomingEvents)
	// keep the connection alive every 20s with a ping
	go ws.Keepalive(20 * time.Second)

	// process outgoing messages from chOutgoing
	go func() {
		for {
			select {
			case msg := <-chOutgoingMessages:
				log.Printf("Sending message %+v\n", msg)
				if err := ws.SendMessage(&msg); err != nil {
					log.Printf("Error: %s\n", err.Error())
				}
			}
		}
	}()

	// process incoming messages
	for {
		select {
		case msg := <-chIncomingEvents:
			//log.Printf("Received event:\n")
			switch msg.Data.(type) {
			case *slack.MessageEvent:
				msgevent := msg.Data.(*slack.MessageEvent)

				// if we didnt have trouble pulling the timestamp out, lets discard if it happened
				// before socketEstablished
				if ts, err := strconv.ParseInt(strings.Split(msgevent.Timestamp, ".")[0], 10, 64); err == nil {
					if socketEstablished > ts {
						log.Printf("Ignoring message %s at %d, which was sent before we started listening\n", msgevent.Msg.Text, ts)
						continue
					}
				} else {
					log.Printf("Unable to parse timestamp %s: %s\n", msgevent.Timestamp, err.Error())
				}
				if msgevent.Msg.Text == "" {
					continue
				}

				log.Printf("Processing: %s\n", msgevent.Msg.Text)
				for _, handler := range messagehandlers {
					//log.Printf("Testing handler %s...\n", handler.Name)
					handled, err := handler.Function(msgevent, chOutgoingMessages)
					if err != nil {
						log.Printf("Error handling message with %s: %s\n", handler.Name, err.Error())
						continue
					}
					if handled {
						log.Printf("%s handled message %s\n", handler.Name, msgevent.Msg.Text)
						break
					}
				}
			}
		}
	}

}
<commit_msg>disable wtf handler<commit_after>package main

import (
	"encoding/json"
	"flag"
	c "github.com/byxorna/collinsbot/collins"
	"github.com/nlopes/slack"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

var (
	cli struct {
		file    string
		token   string
		botname string
		debug   bool
	}
	settings   Settings
	api        *slack.Slack
	ws         *slack.SlackWS
	postParams slack.PostMessageParameters
	collins    *c.Client

	botIdentity *slack.AuthTestResponse

	// message handlers are functions that process a message event
	// similar to http route handlers. The first to return true stops processing
	messagehandlers = []Handler{
		Handler{"Help", HelpHandler},
		Handler{"YouAlive", YouAliveHandler},
		Handler{"AssetTag", AssetTagHandler},
		Handler{"AssetHostname", AssetHostnameHandler},
		//		Handler{"WTF", WTFHandler},
	}

	helpinfo = map[string]string{
		"help": "show this help output",
		"yt?":  "see if I am still alive",
		"mention any asset tag or hostname": "get a link to the asset",
	}
)

func init() {
	flag.StringVar(&cli.token, "token", "", "Slack API token")
	flag.StringVar(&cli.botname, "botname", "", "Bot name")
	flag.StringVar(&cli.file, "config", "", "File containing Slack API token")
	flag.BoolVar(&cli.debug, "debug", false, "Turn on Slack API debugging")
	flag.Parse()
}

func main() {
	if cli.file != "" {
		log.Printf("Loading config from %s\n", cli.file)
		f, err := os.Open(cli.file)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		err = json.NewDecoder(f).Decode(&settings)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Fatal("You need to pass a json file to -config")
	}

	// override whats in the settings with whats on the cli
	if cli.token != "" {
		log.Printf("Slack token passed via CLI: %s\n", cli.token)
		settings.Token = cli.token
	}
	if settings.Botname == "" || cli.botname != "" {
		settings.Botname = cli.botname
	}

	if settings.Token == "" {
		log.Fatal("You need to give me an API token!")
	}

	collins = c.New(settings.Collins.Username, settings.Collins.Password, settings.Collins.Host)

	// set up posting params
	postParams = slack.NewPostMessageParameters()
	postParams.Username = settings.Botname
	//postParams.LinkNames = 1
	// we will perform proper formatting per https://api.slack.com/docs/formatting, do make the server do no processing
	postParams.Parse = "none"

	api = slack.New(settings.Token)
	api.SetDebug(cli.debug)
	authresp, err := api.AuthTest()
	if err != nil {
		log.Fatal(err)
	}
	botIdentity = authresp
	log.Printf("Authed with Slack successfully as %s (%s)\n", botIdentity.User, botIdentity.UserId)

	chIncomingEvents := make(chan slack.SlackEvent)
	chOutgoingMessages := make(chan slack.OutgoingMessage)
	ws, err = api.StartRTM("", "https://www.tumblr.com")
	if err != nil {
		log.Fatal("Unable to start realtime messaging websocket: %s\n", err.Error())
	}

	// send incoming events into the chIncomingEvents channel
	// and record when we started listening for events so we can ignore those which happened earlier
	var socketEstablished = time.Now().Unix()
	go ws.HandleIncomingEvents(chIncomingEvents)
	// keep the connection alive every 20s with a ping
	go ws.Keepalive(20 * time.Second)

	// process outgoing messages from chOutgoing
	go func() {
		for {
			select {
			case msg := <-chOutgoingMessages:
				log.Printf("Sending message %+v\n", msg)
				if err := ws.SendMessage(&msg); err != nil {
					log.Printf("Error: %s\n", err.Error())
				}
			}
		}
	}()

	// process incoming messages
	for {
		select {
		case msg := <-chIncomingEvents:
			//log.Printf("Received event:\n")
			switch msg.Data.(type) {
			case *slack.MessageEvent:
				msgevent := msg.Data.(*slack.MessageEvent)

				// if we didnt have trouble pulling the timestamp out, lets discard if it happened
				// before socketEstablished
				if ts, err := strconv.ParseInt(strings.Split(msgevent.Timestamp, ".")[0], 10, 64); err == nil {
					if socketEstablished > ts {
						log.Printf("Ignoring message %s at %d, which was sent before we started listening\n", msgevent.Msg.Text, ts)
						continue
					}
				} else {
					log.Printf("Unable to parse timestamp %s: %s\n", msgevent.Timestamp, err.Error())
				}
				if msgevent.Msg.Text == "" {
					continue
				}

				log.Printf("Processing: %s\n", msgevent.Msg.Text)
				for _, handler := range messagehandlers {
					//log.Printf("Testing handler %s...\n", handler.Name)
					handled, err := handler.Function(msgevent, chOutgoingMessages)
					if err != nil {
						log.Printf("Error handling message with %s: %s\n", handler.Name, err.Error())
						continue
					}
					if handled {
						log.Printf("%s handled message %s\n", handler.Name, msgevent.Msg.Text)
						break
					}
				}
			}
		}
	}

}
<|endoftext|>


<commit_before>package main

import (
	"github.com/jeffjen/machine/driver/aws"
	"github.com/jeffjen/machine/driver/generic"

	"github.com/codegangsta/cli"

	"os"
)

const (
	DEFAULT_CERT_PATH = "~/.machine"

	DEFAULT_ORGANIZATION_PLACEMENT_NAME = "podd.org"

	DEFAULT_MACHINE_PORT = "22"
)

func main() {
	app := cli.NewApp()
	app.Version = "0.0.1"
	app.Name = "machine"
	app.Usage = "Create/Bootstrap machine to use with Docker engine"
	app.EnableBashCompletion = true
	app.Authors = []cli.Author{
		cli.Author{"Yi-Hung Jen", "yihungjen@gmail.com"},
	}
	app.Commands = []cli.Command{
		ListInstanceCommand(),
		InstanceCommand("start", "Start"),
		InstanceCommand("stop", "Stop"),
		InstanceCommand("rm", "Remove"),
		EnvCommand(),
		ExecCommand(),
		TlsCommand(),
		aws.NewCommand(),
		generic.NewCommand(),
	}
	app.Flags = []cli.Flag{
		cli.StringFlag{Name: "certpath", Value: DEFAULT_CERT_PATH, Usage: "Certificate path"},
		cli.StringFlag{Name: "organization", Value: DEFAULT_ORGANIZATION_PLACEMENT_NAME, Usage: "Organization for CA"},
	}
	app.Before = nil
	app.Action = nil
	app.Run(os.Args)
}
<commit_msg>NIT: remove naming<commit_after>package main

import (
	"github.com/jeffjen/machine/driver/aws"
	"github.com/jeffjen/machine/driver/generic"

	"github.com/codegangsta/cli"

	"os"
)

const (
	DEFAULT_CERT_PATH = "~/.machine"

	DEFAULT_ORGANIZATION_PLACEMENT_NAME = "podd.org"

	DEFAULT_MACHINE_PORT = "22"
)

func main() {
	app := cli.NewApp()
	app.Version = "0.0.1"
	app.Name = "machine"
	app.Usage = "Create/Bootstrap machine to use with Docker engine"
	app.EnableBashCompletion = true
	app.Authors = []cli.Author{
		cli.Author{"Yi-Hung Jen", "yihungjen@gmail.com"},
	}
	app.Commands = []cli.Command{
		ListInstanceCommand(),
		InstanceCommand("start", "Start"),
		InstanceCommand("stop", "Stop"),
		InstanceCommand("rm", "Remove And Terminate"),
		EnvCommand(),
		ExecCommand(),
		TlsCommand(),
		aws.NewCommand(),
		generic.NewCommand(),
	}
	app.Flags = []cli.Flag{
		cli.StringFlag{Name: "certpath", Value: DEFAULT_CERT_PATH, Usage: "Certificate path"},
		cli.StringFlag{Name: "organization", Value: DEFAULT_ORGANIZATION_PLACEMENT_NAME, Usage: "Organization for CA"},
	}
	app.Before = nil
	app.Action = nil
	app.Run(os.Args)
}
<|endoftext|>


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

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"

	"github.com/line/line-bot-sdk-go/linebot"
)
/*
var bot *linebot.Client
var eggyoID = "ufa92a3a52f197e19bfddeb5ca0595e93"
var logNof = "open"

type GeoContent struct {
	LatLong string `json:"latLon"`
	Utm     string `json:"utm"`
	Mgrs    string `json:"mgrs"`
}

type ResultGeoLoc struct {
	Results GeoContent `json:"result"`
}

func getGeoLoc(body []byte) (*ResultGeoLoc, error) {
	var s = new(ResultGeoLoc)
	err := json.Unmarshal(body, &s)
	if err != nil {
		fmt.Println("whoops:", err)
	}
	return s, err
}*/

func main() {

	bot, err := linebot.New(
		os.Getenv("ChannelSecret"),
		os.Getenv("MID"),
	)
	if err != nil {
		log.Fatal(err)
	}
	// Setup HTTP Server for receiving requests from LINE platform
		http.HandleFunc("/callback", func(w http.ResponseWriter, req *http.Request) {
			events, err := bot.ParseRequest(req)
			if err != nil {
				if err == linebot.ErrInvalidSignature {
					w.WriteHeader(400)
				} else {
					w.WriteHeader(500)
				}
				return
			}
			for _, event := range events {
				if event.Type == linebot.EventTypeMessage {
					switch message := event.Message.(type) {
					case *linebot.TextMessage:
						if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(message.Text)).Do(); err != nil {
							log.Print(err)
						}
					}
				}
			}
		})
		// This is just sample code.
		// For actual use, you must support HTTPS by using `ListenAndServeTLS`, a reverse proxy or something else.
		if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
			log.Fatal(err)
		}
}
/*
func callbackHandler(w http.ResponseWriter, r *http.Request) {

	received, err := bot.ParseRequest(r)
	if err != nil {
		if err == linebot.ErrInvalidSignature {
			w.WriteHeader(400)
		} else {
			w.WriteHeader(500)
		}
		return
	}
	for _, result := range received.Results {
		content := result.Content()
		log.Println("-->", content)

		//Log detail receive content
		if content != nil {
			log.Println("RECEIVE Msg:", content.IsMessage, " OP:", content.IsOperation, " type:", content.ContentType, " from:", content.From, "to:", content.To, " ID:", content.ID)
		}
		// user add friend
		if content != nil && content.IsOperation && content.OpType == linebot.OpTypeAddedAsFriend {
			out := fmt.Sprintf("Bot แปลงพิกัด Eggyo\nวิธีใช้\nเพียงแค่กดแชร์ Location ที่ต้องการ ระบบจะทำการแปลง Location เป็นพิกัดระบบต่างๆ และหาความสูงจากระดับน้ำทะเลให้\n\nหรือจะพูดคุยกับ bot ก็ได้\nกด #help เพื่อดูวิธีใช้อื่นๆ \nติดต่อผู้พัฒนา LINE ID : eggyo")
			//result.RawContent.Params[0] is who send your bot friend added operation, otherwise you cannot get in content or operation content.
			_, err = bot.SendText([]string{content.From}, out)
			if logNof == "open" {
				bot.SendText([]string{eggyoID}, "bot has a new friend :"+content.From)
			}

			addNewUser(content.From)

			if err != nil {
				log.Println(err)
			}
		}

		if content != nil && content.IsMessage && content.ContentType == linebot.ContentTypeText {

			text, err := content.TextContent()
			if logNof == "open" {
				bot.SendText([]string{eggyoID}, "bot get msg:"+text.Text+"\nfrom :"+content.From)
			}
			// reply message
			var processedText = messageCheck(text.Text)
			_, err = bot.SendText([]string{content.From}, processedText)

			if err != nil {
				log.Println(err)
			}
		}
		if content != nil && content.ContentType == linebot.ContentTypeLocation {
			_, err = bot.SendText([]string{content.From}, "ระบบกำลังประมวลผล...")

			loc, err := content.LocationContent()

			// add eggyo geo test//
			resp, err := http.Get("http://eggyo-geo-node.herokuapp.com/geo/" + FloatToString(loc.Latitude) + "," + FloatToString(loc.Longitude))
			if err != nil {
				println(err.Error())
				return
			}
			defer resp.Body.Close()
			body, err := ioutil.ReadAll(resp.Body)
			log.Println(string(body))

			var elev = callGoogleElev(loc.Latitude, loc.Longitude)
			geo, err := getGeoLoc([]byte(body))
			_, err = bot.SendText([]string{content.From}, "LatLong :"+geo.Results.LatLong)
			_, err = bot.SendText([]string{content.From}, "Utm :"+geo.Results.Utm+"\n\nMgrs :"+geo.Results.Mgrs+"\n\nAltitude :"+elev)
			if logNof == "open" {
				bot.SendText([]string{eggyoID}, "bot get loc:"+geo.Results.Mgrs+"\nfrom :"+content.From)
			}
			if err != nil {
				log.Println(err)
			}
		}
	}
	*/
}
<commit_msg>v.5.1.1<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"log"
	"net/http"
	"os"

	"github.com/line/line-bot-sdk-go/linebot"
)

/*
var bot *linebot.Client
var eggyoID = "ufa92a3a52f197e19bfddeb5ca0595e93"
var logNof = "open"

type GeoContent struct {
	LatLong string `json:"latLon"`
	Utm     string `json:"utm"`
	Mgrs    string `json:"mgrs"`
}

type ResultGeoLoc struct {
	Results GeoContent `json:"result"`
}

func getGeoLoc(body []byte) (*ResultGeoLoc, error) {
	var s = new(ResultGeoLoc)
	err := json.Unmarshal(body, &s)
	if err != nil {
		fmt.Println("whoops:", err)
	}
	return s, err
}*/

func main() {

	bot, err := linebot.New(
		os.Getenv("ChannelSecret"),
		os.Getenv("MID"),
	)
	if err != nil {
		log.Fatal(err)
	}
	// Setup HTTP Server for receiving requests from LINE platform
	http.HandleFunc("/callback", func(w http.ResponseWriter, req *http.Request) {
		events, err := bot.ParseRequest(req)
		if err != nil {
			if err == linebot.ErrInvalidSignature {
				w.WriteHeader(400)
			} else {
				w.WriteHeader(500)
			}
			return
		}
		for _, event := range events {
			if event.Type == linebot.EventTypeMessage {
				switch message := event.Message.(type) {
				case *linebot.TextMessage:
					if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(message.Text)).Do(); err != nil {
						log.Print(err)
					}
				}
			}
		}
	})
	// This is just sample code.
	// For actual use, you must support HTTPS by using `ListenAndServeTLS`, a reverse proxy or something else.
	if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
		log.Fatal(err)
	}
}

/*
func callbackHandler(w http.ResponseWriter, r *http.Request) {

	received, err := bot.ParseRequest(r)
	if err != nil {
		if err == linebot.ErrInvalidSignature {
			w.WriteHeader(400)
		} else {
			w.WriteHeader(500)
		}
		return
	}
	for _, result := range received.Results {
		content := result.Content()
		log.Println("-->", content)

		//Log detail receive content
		if content != nil {
			log.Println("RECEIVE Msg:", content.IsMessage, " OP:", content.IsOperation, " type:", content.ContentType, " from:", content.From, "to:", content.To, " ID:", content.ID)
		}
		// user add friend
		if content != nil && content.IsOperation && content.OpType == linebot.OpTypeAddedAsFriend {
			out := fmt.Sprintf("Bot แปลงพิกัด Eggyo\nวิธีใช้\nเพียงแค่กดแชร์ Location ที่ต้องการ ระบบจะทำการแปลง Location เป็นพิกัดระบบต่างๆ และหาความสูงจากระดับน้ำทะเลให้\n\nหรือจะพูดคุยกับ bot ก็ได้\nกด #help เพื่อดูวิธีใช้อื่นๆ \nติดต่อผู้พัฒนา LINE ID : eggyo")
			//result.RawContent.Params[0] is who send your bot friend added operation, otherwise you cannot get in content or operation content.
			_, err = bot.SendText([]string{content.From}, out)
			if logNof == "open" {
				bot.SendText([]string{eggyoID}, "bot has a new friend :"+content.From)
			}

			addNewUser(content.From)

			if err != nil {
				log.Println(err)
			}
		}

		if content != nil && content.IsMessage && content.ContentType == linebot.ContentTypeText {

			text, err := content.TextContent()
			if logNof == "open" {
				bot.SendText([]string{eggyoID}, "bot get msg:"+text.Text+"\nfrom :"+content.From)
			}
			// reply message
			var processedText = messageCheck(text.Text)
			_, err = bot.SendText([]string{content.From}, processedText)

			if err != nil {
				log.Println(err)
			}
		}
		if content != nil && content.ContentType == linebot.ContentTypeLocation {
			_, err = bot.SendText([]string{content.From}, "ระบบกำลังประมวลผล...")

			loc, err := content.LocationContent()

			// add eggyo geo test//
			resp, err := http.Get("http://eggyo-geo-node.herokuapp.com/geo/" + FloatToString(loc.Latitude) + "," + FloatToString(loc.Longitude))
			if err != nil {
				println(err.Error())
				return
			}
			defer resp.Body.Close()
			body, err := ioutil.ReadAll(resp.Body)
			log.Println(string(body))

			var elev = callGoogleElev(loc.Latitude, loc.Longitude)
			geo, err := getGeoLoc([]byte(body))
			_, err = bot.SendText([]string{content.From}, "LatLong :"+geo.Results.LatLong)
			_, err = bot.SendText([]string{content.From}, "Utm :"+geo.Results.Utm+"\n\nMgrs :"+geo.Results.Mgrs+"\n\nAltitude :"+elev)
			if logNof == "open" {
				bot.SendText([]string{eggyoID}, "bot get loc:"+geo.Results.Mgrs+"\nfrom :"+content.From)
			}
			if err != nil {
				log.Println(err)
			}
		}
	}
*/
<|endoftext|>


<commit_before>package main

import (
	"context"
	"flag"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"

	"cloud.google.com/go/trace"
)

// TODO(jbd): Support HTTPS.

var (
	projectID     string
	listen        string
	target        string
	tlsCert       string
	tlsKey        string
	enableLogging bool
)

func main() {
	ctx := context.Background()

	flag.StringVar(&projectID, "project", "", "google cloud project ID")
	flag.StringVar(&listen, "http", ":6996", "host:port proxy listens")
	flag.StringVar(&target, "target", "", "target server")
	flag.StringVar(&tlsCert, "tls-cert", "", "TLS cert file to start an HTTPS proxy")
	flag.StringVar(&tlsKey, "tls-key", "", "TLS key file to start an HTTPS proxy")
	flag.BoolVar(&enableLogging, "enable-logging", false, "set to enable logging to stackdriver")
	flag.Parse()

	// TODO(jbd): Handle missing required flags.

	tc, err := trace.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Cannot initiate trace client: %v", err)
	}

	url, err := url.Parse(target)
	if err != nil {
		log.Fatal(err)
	}

	proxy := httputil.NewSingleHostReverseProxy(url)
	proxy.Transport = &transport{
		Trace: tc,
	}

	if tlsCert != "" && tlsKey != "" {
		log.Fatal(http.ListenAndServeTLS(listen, tlsCert, tlsKey, proxy))
	} else {
		log.Fatal(http.ListenAndServe(listen, proxy))
	}
}

type transport struct {
	Trace *trace.Client
}

func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
	s := t.Trace.SpanFromRequest(req)
	defer s.FinishWait()

	resp, err := http.DefaultTransport.RoundTrip(req)
	return resp, err
}
<commit_msg>auto detect projectID on GCE<commit_after>package main

import (
	"context"
	"flag"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"

	"cloud.google.com/go/compute/metadata"
	"cloud.google.com/go/trace"
)

// TODO(jbd): Support HTTPS.

var (
	projectID     string
	listen        string
	target        string
	tlsCert       string
	tlsKey        string
	enableLogging bool
)

func main() {
	ctx := context.Background()

	flag.StringVar(&projectID, "project", "", "google cloud project ID")
	flag.StringVar(&listen, "http", ":6996", "host:port proxy listens")
	flag.StringVar(&target, "target", "", "target server")
	flag.StringVar(&tlsCert, "tls-cert", "", "TLS cert file to start an HTTPS proxy")
	flag.StringVar(&tlsKey, "tls-key", "", "TLS key file to start an HTTPS proxy")
	flag.BoolVar(&enableLogging, "enable-logging", false, "set to enable logging to stackdriver")
	flag.Parse()

	if projectID == "" {
		// Try to retrieve it from metadata server.
		if metadata.OnGCE() {
			pid, err := metadata.ProjectID()
			if err != nil {
				log.Fatalf("Cannot get project ID from metadata server: %v", err)
			}
			projectID = pid
		}
	}
	// TODO(jbd): Show usage if projectID is not set.

	tc, err := trace.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Cannot initiate trace client: %v", err)
	}

	url, err := url.Parse(target)
	if err != nil {
		log.Fatal(err)
	}

	proxy := httputil.NewSingleHostReverseProxy(url)
	proxy.Transport = &transport{
		Trace: tc,
	}

	if tlsCert != "" && tlsKey != "" {
		log.Fatal(http.ListenAndServeTLS(listen, tlsCert, tlsKey, proxy))
	} else {
		log.Fatal(http.ListenAndServe(listen, proxy))
	}
}

type transport struct {
	Trace *trace.Client
}

func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
	s := t.Trace.SpanFromRequest(req)
	defer s.FinishWait()

	resp, err := http.DefaultTransport.RoundTrip(req)
	return resp, err
}
<|endoftext|>