<commit_before>package main

import (
	"errors"
	"flag"
	"fmt"
	"io"
	"math/rand"
	"os"
	"os/signal"
	"path/filepath"
	"runtime/pprof"
	"strings"
	"time"

	"github.com/BurntSushi/toml"
	"github.com/pilosa/pilosa"
)

// Version holds the version information passed in at compile time.
var Version string

func init() {
	if Version == "" {
		Version = "0.0.0"
	}

	rand.Seed(time.Now().UTC().UnixNano())
}

const (
	// DefaultDataDir is the default data directory.
	DefaultDataDir = "~/.pilosa"
)

func main() {
	m := NewMain()
	m.Server.Handler.Version = Version
	fmt.Fprintf(m.Stderr, "Pilosa %s\n", Version)

	// Parse command line arguments.
	if err := m.ParseFlags(os.Args[1:]); err != nil {
		fmt.Fprintln(m.Stderr, err)
		os.Exit(2)
	}

	// Start CPU profiling.
	if m.CPUProfile != "" {
		f, err := os.Create(m.CPUProfile)
		if err != nil {
			fmt.Fprintf(m.Stderr, "create cpu profile: %v", err)
			os.Exit(1)
		}
		defer f.Close()

		fmt.Fprintln(m.Stderr, "Starting cpu profile")
		pprof.StartCPUProfile(f)
		time.AfterFunc(m.CPUTime, func() {
			fmt.Fprintln(m.Stderr, "Stopping cpu profile")
			pprof.StopCPUProfile()
			f.Close()
		})
	}

	// Execute the program.
	if err := m.Run(); err != nil {
		fmt.Fprintln(m.Stderr, err)
		fmt.Fprintln(m.Stderr, "stopping profile")
		os.Exit(1)
	}

	// First SIGKILL causes server to shut down gracefully.
	c := make(chan os.Signal, 2)
	signal.Notify(c, os.Interrupt)
	sig := <-c
	fmt.Fprintf(m.Stderr, "Received %s; gracefully shutting down...\n", sig.String())

	// Second signal causes a hard shutdown.
	go func() { <-c; os.Exit(1) }()

	if err := m.Close(); err != nil {
		fmt.Fprintln(m.Stderr, err)
		os.Exit(1)
	}
}

// Main represents the main program execution.
type Main struct {
	Server *pilosa.Server

	// Configuration options.
	ConfigPath string
	Config     *pilosa.Config

	// Profiling options.
	CPUProfile string
	CPUTime    time.Duration

	// Standard input/output
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

// NewMain returns a new instance of Main.
func NewMain() *Main {
	return &Main{
		Server: pilosa.NewServer(),
		Config: pilosa.NewConfig(),

		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
}

// Run executes the main program execution.
func (m *Main) Run(args ...string) error {
	// Notify user of config file.
	if m.ConfigPath != "" {
		fmt.Fprintf(m.Stdout, "Using config: %s\n", m.ConfigPath)
	}

	// Setup logging output.
	m.Server.LogOutput = m.Stderr

	// Configure index.
	fmt.Fprintf(m.Stderr, "Using data from: %s\n", m.Config.DataDir)
	m.Server.Index.Path = m.Config.DataDir
	m.Server.Index.Stats = pilosa.NewExpvarStatsClient()

	// Build cluster from config file.
	m.Server.Host = m.Config.Host
	m.Server.Cluster = m.Config.PilosaCluster()

	// Set configuration options.
	m.Server.AntiEntropyInterval = time.Duration(m.Config.AntiEntropy.Interval)

	// Initialize server.
	if err := m.Server.Open(); err != nil {
		return err
	}

	fmt.Fprintf(m.Stderr, "Listening as http://%s\n", m.Server.Host)

	return nil
}

// Close shuts down the server.
func (m *Main) Close() error {
	return m.Server.Close()
}

// ParseFlags parses command line flags from args.
func (m *Main) ParseFlags(args []string) error {
	fs := flag.NewFlagSet("pilosa", flag.ContinueOnError)
	fs.StringVar(&m.CPUProfile, "cpuprofile", "", "cpu profile")
	fs.DurationVar(&m.CPUTime, "cputime", 30*time.Second, "cpu profile duration")
	fs.StringVar(&m.ConfigPath, "config", "", "config path")
	fs.SetOutput(m.Stderr)
	if err := fs.Parse(args); err != nil {
		return err
	}

	// Load config, if specified.
	if m.ConfigPath != "" {
		if _, err := toml.DecodeFile(m.ConfigPath, &m.Config); err != nil {
			return err
		}
	}

	// Use default data directory if one is not specified.
	if m.Config.DataDir == "" {
		m.Config.DataDir = DefaultDataDir
	}

	// Expand home directory.
	prefix := "~" + string(filepath.Separator)
	if strings.HasPrefix(m.Config.DataDir, prefix) {
		//	u, err := user.Current()
		HomeDir := os.Getenv("HOME")
		/*if err != nil {
			return err
		} else*/if HomeDir == "" {
			return errors.New("data directory not specified and no home dir available")
		}
		m.Config.DataDir = filepath.Join(HomeDir, strings.TrimPrefix(m.Config.DataDir, prefix))
	}

	return nil
}
<commit_msg>for the default version number, include the `v`<commit_after>package main

import (
	"errors"
	"flag"
	"fmt"
	"io"
	"math/rand"
	"os"
	"os/signal"
	"path/filepath"
	"runtime/pprof"
	"strings"
	"time"

	"github.com/BurntSushi/toml"
	"github.com/pilosa/pilosa"
)

// Version holds the version information passed in at compile time.
var Version string

func init() {
	if Version == "" {
		Version = "v0.0.0"
	}

	rand.Seed(time.Now().UTC().UnixNano())
}

const (
	// DefaultDataDir is the default data directory.
	DefaultDataDir = "~/.pilosa"
)

func main() {
	m := NewMain()
	m.Server.Handler.Version = Version
	fmt.Fprintf(m.Stderr, "Pilosa %s\n", Version)

	// Parse command line arguments.
	if err := m.ParseFlags(os.Args[1:]); err != nil {
		fmt.Fprintln(m.Stderr, err)
		os.Exit(2)
	}

	// Start CPU profiling.
	if m.CPUProfile != "" {
		f, err := os.Create(m.CPUProfile)
		if err != nil {
			fmt.Fprintf(m.Stderr, "create cpu profile: %v", err)
			os.Exit(1)
		}
		defer f.Close()

		fmt.Fprintln(m.Stderr, "Starting cpu profile")
		pprof.StartCPUProfile(f)
		time.AfterFunc(m.CPUTime, func() {
			fmt.Fprintln(m.Stderr, "Stopping cpu profile")
			pprof.StopCPUProfile()
			f.Close()
		})
	}

	// Execute the program.
	if err := m.Run(); err != nil {
		fmt.Fprintln(m.Stderr, err)
		fmt.Fprintln(m.Stderr, "stopping profile")
		os.Exit(1)
	}

	// First SIGKILL causes server to shut down gracefully.
	c := make(chan os.Signal, 2)
	signal.Notify(c, os.Interrupt)
	sig := <-c
	fmt.Fprintf(m.Stderr, "Received %s; gracefully shutting down...\n", sig.String())

	// Second signal causes a hard shutdown.
	go func() { <-c; os.Exit(1) }()

	if err := m.Close(); err != nil {
		fmt.Fprintln(m.Stderr, err)
		os.Exit(1)
	}
}

// Main represents the main program execution.
type Main struct {
	Server *pilosa.Server

	// Configuration options.
	ConfigPath string
	Config     *pilosa.Config

	// Profiling options.
	CPUProfile string
	CPUTime    time.Duration

	// Standard input/output
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

// NewMain returns a new instance of Main.
func NewMain() *Main {
	return &Main{
		Server: pilosa.NewServer(),
		Config: pilosa.NewConfig(),

		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
}

// Run executes the main program execution.
func (m *Main) Run(args ...string) error {
	// Notify user of config file.
	if m.ConfigPath != "" {
		fmt.Fprintf(m.Stdout, "Using config: %s\n", m.ConfigPath)
	}

	// Setup logging output.
	m.Server.LogOutput = m.Stderr

	// Configure index.
	fmt.Fprintf(m.Stderr, "Using data from: %s\n", m.Config.DataDir)
	m.Server.Index.Path = m.Config.DataDir
	m.Server.Index.Stats = pilosa.NewExpvarStatsClient()

	// Build cluster from config file.
	m.Server.Host = m.Config.Host
	m.Server.Cluster = m.Config.PilosaCluster()

	// Set configuration options.
	m.Server.AntiEntropyInterval = time.Duration(m.Config.AntiEntropy.Interval)

	// Initialize server.
	if err := m.Server.Open(); err != nil {
		return err
	}

	fmt.Fprintf(m.Stderr, "Listening as http://%s\n", m.Server.Host)

	return nil
}

// Close shuts down the server.
func (m *Main) Close() error {
	return m.Server.Close()
}

// ParseFlags parses command line flags from args.
func (m *Main) ParseFlags(args []string) error {
	fs := flag.NewFlagSet("pilosa", flag.ContinueOnError)
	fs.StringVar(&m.CPUProfile, "cpuprofile", "", "cpu profile")
	fs.DurationVar(&m.CPUTime, "cputime", 30*time.Second, "cpu profile duration")
	fs.StringVar(&m.ConfigPath, "config", "", "config path")
	fs.SetOutput(m.Stderr)
	if err := fs.Parse(args); err != nil {
		return err
	}

	// Load config, if specified.
	if m.ConfigPath != "" {
		if _, err := toml.DecodeFile(m.ConfigPath, &m.Config); err != nil {
			return err
		}
	}

	// Use default data directory if one is not specified.
	if m.Config.DataDir == "" {
		m.Config.DataDir = DefaultDataDir
	}

	// Expand home directory.
	prefix := "~" + string(filepath.Separator)
	if strings.HasPrefix(m.Config.DataDir, prefix) {
		//	u, err := user.Current()
		HomeDir := os.Getenv("HOME")
		/*if err != nil {
			return err
		} else*/if HomeDir == "" {
			return errors.New("data directory not specified and no home dir available")
		}
		m.Config.DataDir = filepath.Join(HomeDir, strings.TrimPrefix(m.Config.DataDir, prefix))
	}

	return nil
}
<|endoftext|>


<commit_before>// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"sort"

	"golang.org/x/tools/present"
)

func init() {
	http.HandleFunc("/", dirHandler)
}

// dirHandler serves a directory listing for the requested path, rooted at basePath.
func dirHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/favicon.ico" {
		http.Error(w, "not found", 404)
		return
	}
	const base = "."
	name := filepath.Join(base, r.URL.Path)
	if isDoc(name) {
		err := renderDoc(w, name)
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), 500)
		}
		return
	}
	if isDir, err := dirList(w, name); err != nil {
		log.Println(err)
		http.Error(w, err.Error(), 500)
		return
	} else if isDir {
		return
	}
	http.FileServer(http.Dir(base)).ServeHTTP(w, r)
}

func isDoc(path string) bool {
	_, ok := contentTemplate[filepath.Ext(path)]
	return ok
}

var (
	// dirListTemplate holds the front page template.
	dirListTemplate *template.Template

	// contentTemplate maps the presentable file extensions to the
	// template to be executed.
	contentTemplate map[string]*template.Template
)

func initTemplates(base string) error {
	// Locate the template file.
	actionTmpl := filepath.Join(base, "templates/action.tmpl")

	contentTemplate = make(map[string]*template.Template)

	for ext, contentTmpl := range map[string]string{
		".slide":   "slides.tmpl",
		".article": "article.tmpl",
	} {
		contentTmpl = filepath.Join(base, "templates", contentTmpl)

		// Read and parse the input.
		tmpl := present.Template()
		tmpl = tmpl.Funcs(template.FuncMap{"playable": playable})
		if _, err := tmpl.ParseFiles(actionTmpl, contentTmpl); err != nil {
			return err
		}
		contentTemplate[ext] = tmpl
	}

	var err error
	dirListTemplate, err = template.ParseFiles(filepath.Join(base, "templates/dir.tmpl"))
	if err != nil {
		return err
	}

	return nil
}

// renderDoc reads the present file, gets its template representation,
// and executes the template, sending output to w.
func renderDoc(w io.Writer, docFile string) error {
	// Read the input and build the doc structure.
	doc, err := parse(docFile, 0)
	if err != nil {
		return err
	}

	// Find which template should be executed.
	tmpl := contentTemplate[filepath.Ext(docFile)]

	// Execute the template.
	return doc.Render(w, tmpl)
}

func parse(name string, mode present.ParseMode) (*present.Doc, error) {
	f, err := os.Open(name)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return present.Parse(f, name, 0)
}

// dirList scans the given path and writes a directory listing to w.
// It parses the first part of each .slide file it encounters to display the
// presentation title in the listing.
// If the given path is not a directory, it returns (isDir == false, err == nil)
// and writes nothing to w.
func dirList(w io.Writer, name string) (isDir bool, err error) {
	f, err := os.Open(name)
	if err != nil {
		return false, err
	}
	defer f.Close()
	fi, err := f.Stat()
	if err != nil {
		return false, err
	}
	if isDir = fi.IsDir(); !isDir {
		return false, nil
	}
	fis, err := f.Readdir(0)
	if err != nil {
		return false, err
	}
	d := &dirListData{Path: name}
	for _, fi := range fis {
		// skip the golang.org directory
		if name == "." && fi.Name() == "golang.org" {
			continue
		}
		e := dirEntry{
			Name: fi.Name(),
			Path: filepath.ToSlash(filepath.Join(name, fi.Name())),
		}
		if fi.IsDir() && showDir(e.Name) {
			d.Dirs = append(d.Dirs, e)
			continue
		}
		if isDoc(e.Name) {
			if p, err := parse(e.Path, present.TitlesOnly); err != nil {
				log.Println(err)
			} else {
				e.Title = p.Title
			}
			switch filepath.Ext(e.Path) {
			case ".article":
				d.Articles = append(d.Articles, e)
			case ".slide":
				d.Slides = append(d.Slides, e)
			}
		} else if showFile(e.Name) {
			d.Other = append(d.Other, e)
		}
	}
	if d.Path == "." {
		d.Path = ""
	}
	sort.Sort(d.Dirs)
	sort.Sort(d.Slides)
	sort.Sort(d.Articles)
	sort.Sort(d.Other)
	return true, dirListTemplate.Execute(w, d)
}

// showFile reports whether the given file should be displayed in the list.
func showFile(n string) bool {
	switch filepath.Ext(n) {
	case ".pdf":
	case ".html":
	case ".go":
	default:
		return isDoc(n)
	}
	return true
}

// showDir reports whether the given directory should be displayed in the list.
func showDir(n string) bool {
	if len(n) > 0 && (n[0] == '.' || n[0] == '_') || n == "present" {
		return false
	}
	return true
}

type dirListData struct {
	Path                          string
	Dirs, Slides, Articles, Other dirEntrySlice
}

type dirEntry struct {
	Name, Path, Title string
}

type dirEntrySlice []dirEntry

func (s dirEntrySlice) Len() int           { return len(s) }
func (s dirEntrySlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s dirEntrySlice) Less(i, j int) bool { return s[i].Name < s[j].Name }
<commit_msg>cmd/present: add request address to logged errors<commit_after>// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"html/template"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"sort"

	"golang.org/x/tools/present"
)

func init() {
	http.HandleFunc("/", dirHandler)
}

// dirHandler serves a directory listing for the requested path, rooted at basePath.
func dirHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/favicon.ico" {
		http.Error(w, "not found", 404)
		return
	}
	const base = "."
	name := filepath.Join(base, r.URL.Path)
	if isDoc(name) {
		err := renderDoc(w, name)
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), 500)
		}
		return
	}
	if isDir, err := dirList(w, name); err != nil {
		addr, _, e := net.SplitHostPort(r.RemoteAddr)
		if e != nil {
			addr = r.RemoteAddr
		}
		log.Printf("request from %s: %s", addr, err)
		http.Error(w, err.Error(), 500)
		return
	} else if isDir {
		return
	}
	http.FileServer(http.Dir(base)).ServeHTTP(w, r)
}

func isDoc(path string) bool {
	_, ok := contentTemplate[filepath.Ext(path)]
	return ok
}

var (
	// dirListTemplate holds the front page template.
	dirListTemplate *template.Template

	// contentTemplate maps the presentable file extensions to the
	// template to be executed.
	contentTemplate map[string]*template.Template
)

func initTemplates(base string) error {
	// Locate the template file.
	actionTmpl := filepath.Join(base, "templates/action.tmpl")

	contentTemplate = make(map[string]*template.Template)

	for ext, contentTmpl := range map[string]string{
		".slide":   "slides.tmpl",
		".article": "article.tmpl",
	} {
		contentTmpl = filepath.Join(base, "templates", contentTmpl)

		// Read and parse the input.
		tmpl := present.Template()
		tmpl = tmpl.Funcs(template.FuncMap{"playable": playable})
		if _, err := tmpl.ParseFiles(actionTmpl, contentTmpl); err != nil {
			return err
		}
		contentTemplate[ext] = tmpl
	}

	var err error
	dirListTemplate, err = template.ParseFiles(filepath.Join(base, "templates/dir.tmpl"))
	if err != nil {
		return err
	}

	return nil
}

// renderDoc reads the present file, gets its template representation,
// and executes the template, sending output to w.
func renderDoc(w io.Writer, docFile string) error {
	// Read the input and build the doc structure.
	doc, err := parse(docFile, 0)
	if err != nil {
		return err
	}

	// Find which template should be executed.
	tmpl := contentTemplate[filepath.Ext(docFile)]

	// Execute the template.
	return doc.Render(w, tmpl)
}

func parse(name string, mode present.ParseMode) (*present.Doc, error) {
	f, err := os.Open(name)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return present.Parse(f, name, 0)
}

// dirList scans the given path and writes a directory listing to w.
// It parses the first part of each .slide file it encounters to display the
// presentation title in the listing.
// If the given path is not a directory, it returns (isDir == false, err == nil)
// and writes nothing to w.
func dirList(w io.Writer, name string) (isDir bool, err error) {
	f, err := os.Open(name)
	if err != nil {
		return false, err
	}
	defer f.Close()
	fi, err := f.Stat()
	if err != nil {
		return false, err
	}
	if isDir = fi.IsDir(); !isDir {
		return false, nil
	}
	fis, err := f.Readdir(0)
	if err != nil {
		return false, err
	}
	d := &dirListData{Path: name}
	for _, fi := range fis {
		// skip the golang.org directory
		if name == "." && fi.Name() == "golang.org" {
			continue
		}
		e := dirEntry{
			Name: fi.Name(),
			Path: filepath.ToSlash(filepath.Join(name, fi.Name())),
		}
		if fi.IsDir() && showDir(e.Name) {
			d.Dirs = append(d.Dirs, e)
			continue
		}
		if isDoc(e.Name) {
			if p, err := parse(e.Path, present.TitlesOnly); err != nil {
				log.Println(err)
			} else {
				e.Title = p.Title
			}
			switch filepath.Ext(e.Path) {
			case ".article":
				d.Articles = append(d.Articles, e)
			case ".slide":
				d.Slides = append(d.Slides, e)
			}
		} else if showFile(e.Name) {
			d.Other = append(d.Other, e)
		}
	}
	if d.Path == "." {
		d.Path = ""
	}
	sort.Sort(d.Dirs)
	sort.Sort(d.Slides)
	sort.Sort(d.Articles)
	sort.Sort(d.Other)
	return true, dirListTemplate.Execute(w, d)
}

// showFile reports whether the given file should be displayed in the list.
func showFile(n string) bool {
	switch filepath.Ext(n) {
	case ".pdf":
	case ".html":
	case ".go":
	default:
		return isDoc(n)
	}
	return true
}

// showDir reports whether the given directory should be displayed in the list.
func showDir(n string) bool {
	if len(n) > 0 && (n[0] == '.' || n[0] == '_') || n == "present" {
		return false
	}
	return true
}

type dirListData struct {
	Path                          string
	Dirs, Slides, Articles, Other dirEntrySlice
}

type dirEntry struct {
	Name, Path, Title string
}

type dirEntrySlice []dirEntry

func (s dirEntrySlice) Len() int           { return len(s) }
func (s dirEntrySlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s dirEntrySlice) Less(i, j int) bool { return s[i].Name < s[j].Name }
<|endoftext|>


<commit_before>// Copyright 2015 CodeIgnition. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"log"

	"golang.org/x/net/context"

	"github.com/codeignition/recon/cmd/recond/config"
	"github.com/codeignition/recon/policy"
	_ "github.com/codeignition/recon/policy/handlers"
	"github.com/nats-io/nats"
)

const agentsAPIPath = "/api/agents" // agents path in the marksman server

// natsEncConn is the opened with the URL obtained from marksman.
// It is populated if the agent registers successfully.
var natsEncConn *nats.EncodedConn

func main() {
	log.SetPrefix("recond: ")

	var marksmanAddr = flag.String("marksman", "http://localhost:3000", "address of the marksman server")
	flag.Parse()

	conf, err := config.Init()
	if err != nil {
		log.Fatalln(err)
	}

	// agent represents a single agent on which the recond
	// is running.
	var agent = &Agent{
		UID: conf.UID,
	}

	err = agent.register(*marksmanAddr)
	if err != nil {
		log.Fatalln(err)
	}

	defer natsEncConn.Close()

	if err := addSystemDataPolicy(conf); err != nil {
		log.Fatal(err)
	}

	go runStoredPolicies(conf)

	natsEncConn.Subscribe(agent.UID, func(s string) {
		fmt.Printf("Received a message: %s\n", s)
	})

	natsEncConn.Subscribe(agent.UID+"_policy", func(subj, reply string, p *policy.Policy) {
		fmt.Printf("Received a Policy: %v\n", p)
		if err := conf.AddPolicy(*p); err != nil {
			natsEncConn.Publish(reply, err.Error())
			return
		}
		if err := conf.Save(); err != nil {
			natsEncConn.Publish(reply, err.Error())
			return
		}
		events, err := p.Execute(context.TODO())
		if err != nil {
			natsEncConn.Publish(reply, err.Error())
			return
		}
		natsEncConn.Publish(reply, "policy ack") // acknowledge
		for e := range events {
			natsEncConn.Publish("policy_events", e)
		}
	})

	// this is just to block the main function from exiting
	c := make(chan struct{})
	<-c
}

func runStoredPolicies(c *config.Config) {
	for _, p := range c.PolicyConfig {
		go func() {
			events, err := p.Execute(context.TODO())
			if err != nil {
				log.Fatal(err) // TODO: send to a nats errors channel
			}
			for e := range events {
				natsEncConn.Publish("policy_events", e)
			}
		}()
	}
}

func addSystemDataPolicy(c *config.Config) error {
	// if the policy already exists, return silently
	for _, p := range c.PolicyConfig {
		if p.Name == "default_system_data" {
			return nil
		}
	}

	p := policy.Policy{
		Name:     "default_system_data",
		AgentUID: c.UID,
		Type:     "system_data",
		M: map[string]string{
			"interval": "5s",
		},
	}
	if err := c.AddPolicy(p); err != nil {
		return err

	}
	if err := c.Save(); err != nil {
		return err
	}
	return nil
}
<commit_msg>fix race condition while running stored policies<commit_after>// Copyright 2015 CodeIgnition. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"log"

	"golang.org/x/net/context"

	"github.com/codeignition/recon/cmd/recond/config"
	"github.com/codeignition/recon/policy"
	_ "github.com/codeignition/recon/policy/handlers"
	"github.com/nats-io/nats"
)

const agentsAPIPath = "/api/agents" // agents path in the marksman server

// natsEncConn is the opened with the URL obtained from marksman.
// It is populated if the agent registers successfully.
var natsEncConn *nats.EncodedConn

func main() {
	log.SetPrefix("recond: ")

	var marksmanAddr = flag.String("marksman", "http://localhost:3000", "address of the marksman server")
	flag.Parse()

	conf, err := config.Init()
	if err != nil {
		log.Fatalln(err)
	}

	// agent represents a single agent on which the recond
	// is running.
	var agent = &Agent{
		UID: conf.UID,
	}

	err = agent.register(*marksmanAddr)
	if err != nil {
		log.Fatalln(err)
	}

	defer natsEncConn.Close()

	if err := addSystemDataPolicy(conf); err != nil {
		log.Fatal(err)
	}

	go runStoredPolicies(conf)

	natsEncConn.Subscribe(agent.UID, func(s string) {
		fmt.Printf("Received a message: %s\n", s)
	})

	natsEncConn.Subscribe(agent.UID+"_policy", func(subj, reply string, p *policy.Policy) {
		fmt.Printf("Received a Policy: %v\n", p)
		if err := conf.AddPolicy(*p); err != nil {
			natsEncConn.Publish(reply, err.Error())
			return
		}
		if err := conf.Save(); err != nil {
			natsEncConn.Publish(reply, err.Error())
			return
		}
		events, err := p.Execute(context.TODO())
		if err != nil {
			natsEncConn.Publish(reply, err.Error())
			return
		}
		natsEncConn.Publish(reply, "policy ack") // acknowledge
		for e := range events {
			natsEncConn.Publish("policy_events", e)
		}
	})

	// this is just to block the main function from exiting
	c := make(chan struct{})
	<-c
}

func runStoredPolicies(c *config.Config) {
	log.Print("adding stored policies...")
	for _, p := range c.PolicyConfig {
		log.Print(p.Name)
		go func(p policy.Policy) {
			events, err := p.Execute(context.TODO())
			if err != nil {
				log.Print(err) // TODO: send to a nats errors channel
			}
			for e := range events {
				natsEncConn.Publish("policy_events", e)
			}
		}(p)
	}
}

func addSystemDataPolicy(c *config.Config) error {
	// if the policy already exists, return silently
	for _, p := range c.PolicyConfig {
		if p.Name == "default_system_data" {
			return nil
		}
	}

	p := policy.Policy{
		Name:     "default_system_data",
		AgentUID: c.UID,
		Type:     "system_data",
		M: map[string]string{
			"interval": "5s",
		},
	}
	if err := c.AddPolicy(p); err != nil {
		return err

	}
	if err := c.Save(); err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"database/sql"
	"fmt"
	"os"

	"github.com/howeyc/gopass"
	_ "github.com/lib/pq"
	"golang.org/x/crypto/bcrypt"
)

func EncryptBcrypt(passwd string) (hash string, err error) {
	hashBytes, err := bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
	hash = string(hashBytes)
	return
}

func updateAuthorRow(connString, uname, passwd, fullname, email, www string) {
	db, err := sql.Open("postgres", connString)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer db.Close()
	//stmt, _ := db.Prepare(`insert into author(id, disp_name, passwd, full_name, email, www)
	//values($1, $2, $3, $4, $5, $6)`)
	stmt, _ := db.Prepare(`update author set
	disp_name=$1, passwd=$2, full_name=$3, email=$4, www=$5
	where id=1`)
	defer stmt.Close()
	passwdHash, err := EncryptBcrypt(passwd)
	if err != nil {
		fmt.Printf("Error in Encrypt(): %s\n", err)
		return
	}
	fmt.Printf("Updating user ID=1...\n")
	fmt.Printf("dbstr: %q\nuname: %q\npasswd: %q\nhash: %q\nfullname: %q\nemail: %q\nwww: %q\n",
		connString, uname, "***", passwdHash, fullname, email, www)
	stmt.Exec(uname, passwdHash, fullname, email, www)
}

func main() {
	dbFile := os.Getenv("RTFBLOG_DB_TEST_URL")
	uname := "rtfb"
	fmt.Printf("New password: ")
	passwd := gopass.GetPasswd()
	fmt.Printf("Confirm: ")
	passwd2 := gopass.GetPasswd()
	if string(passwd2) != string(passwd) {
		panic("Passwords do not match")
	}
	fullname := "Vytautas Šaltenis"
	email := "vytas@rtfb.lt"
	www := "http://rtfb.lt/"
	updateAuthorRow(dbFile, uname, string(passwd), fullname, email, www)
}
<commit_msg>cmd/reset: remove dead code<commit_after>package main

import (
	"database/sql"
	"fmt"
	"os"

	"github.com/howeyc/gopass"
	_ "github.com/lib/pq"
	"golang.org/x/crypto/bcrypt"
)

func EncryptBcrypt(passwd string) (hash string, err error) {
	hashBytes, err := bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
	hash = string(hashBytes)
	return
}

func updateAuthorRow(connString, uname, passwd, fullname, email, www string) {
	db, err := sql.Open("postgres", connString)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer db.Close()
	stmt, _ := db.Prepare(`update author set
	disp_name=$1, passwd=$2, full_name=$3, email=$4, www=$5
	where id=1`)
	defer stmt.Close()
	passwdHash, err := EncryptBcrypt(passwd)
	if err != nil {
		fmt.Printf("Error in Encrypt(): %s\n", err)
		return
	}
	fmt.Printf("Updating user ID=1...\n")
	fmt.Printf("dbstr: %q\nuname: %q\npasswd: %q\nhash: %q\nfullname: %q\nemail: %q\nwww: %q\n",
		connString, uname, "***", passwdHash, fullname, email, www)
	stmt.Exec(uname, passwdHash, fullname, email, www)
}

func main() {
	dbFile := os.Getenv("RTFBLOG_DB_TEST_URL")
	uname := "rtfb"
	fmt.Printf("New password: ")
	passwd := gopass.GetPasswd()
	fmt.Printf("Confirm: ")
	passwd2 := gopass.GetPasswd()
	if string(passwd2) != string(passwd) {
		panic("Passwords do not match")
	}
	fullname := "Vytautas Šaltenis"
	email := "vytas@rtfb.lt"
	www := "http://rtfb.lt/"
	updateAuthorRow(dbFile, uname, string(passwd), fullname, email, www)
}
<|endoftext|>


<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package main

import (
	"github.com/szabba/md/newton"
	"github.com/szabba/md/vect"
)

// A 'picky' force, that doesn't affect some bodies
type PickyForce struct {
	force   newton.Force
	zeroFor []int
}

// Creates a picky version of a force
func NewPicky(f newton.Force, zeroFor ...int) newton.Force {

	return &PickyForce{force: f, zeroFor: zeroFor}
}

func (picky *PickyForce) Accel(bs []*newton.Body, i int) (a vect.Vector) {

	for _, ignored := range picky.zeroFor {

		if ignored == i {

			return vect.Zero
		}
	}

	return picky.force.Accel(bs, i)
}

// Creates a system containing a rectangular grid of m times n particles.
func SetUpRect(m, n int) *newton.System {

	sys := newton.NewSystem(newton.Verlet, m*n)

	for i := 0; i < sys.Bodies(); i++ {

		sys.Body(i).SetMass(1)
	}

	return sys
}

func main() {
}
<commit_msg>Add ParticleRect in cmd/square<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package main

import (
	"github.com/szabba/md/newton"
	"github.com/szabba/md/vect"
)

// A 'picky' force, that doesn't affect some bodies
type PickyForce struct {
	force   newton.Force
	zeroFor []int
}

// Creates a picky version of a force
func NewPicky(f newton.Force, zeroFor ...int) newton.Force {

	return &PickyForce{force: f, zeroFor: zeroFor}
}

func (picky *PickyForce) Accel(bs []*newton.Body, i int) (a vect.Vector) {

	for _, ignored := range picky.zeroFor {

		if ignored == i {

			return vect.Zero
		}
	}

	return picky.force.Accel(bs, i)
}

type ParticleRect struct {
	*newton.System
	rows, cols int
}

// Creates a rectangular grid of particles
func NewRect(rows, cols int) *ParticleRect {

	rect := &ParticleRect{
		rows: rows, cols: cols,
	}

	rect.System = newton.NewSystem(newton.Verlet, rows*cols)

	for i := 0; i < rect.Bodies(); i++ {

		rect.Body(i).SetMass(1)
	}

	return rect
}

func main() {
}
<|endoftext|>


<commit_before>// Copyright 2015 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"

	"github.com/tsuru/config"
	"github.com/tsuru/tsuru/app"
	"github.com/tsuru/tsuru/cmd"
	"github.com/tsuru/tsuru/db"
	"github.com/tsuru/tsuru/migration"
	"github.com/tsuru/tsuru/provision"
	"github.com/tsuru/tsuru/provision/docker"
	"gopkg.in/mgo.v2/bson"
	"launchpad.net/gnuflag"
)

func getProvisioner() (string, error) {
	provisioner, err := config.GetString("provisioner")
	if provisioner == "" {
		provisioner = "docker"
	}
	return provisioner, err
}

type migrateCmd struct {
	fs  *gnuflag.FlagSet
	dry bool
}

func (*migrateCmd) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "migrate",
		Usage: "migrate",
		Desc:  "Runs migrations from previous versions of tsr",
	}
}

func (c *migrateCmd) Run(context *cmd.Context, client *cmd.Client) error {
	err := migration.Register("migrate-docker-images", c.migrateImages)
	if err != nil {
		return err
	}
	err := migration.Register("migrate-pool", c.migratePool)
	if err != nil {
		return err
	}
	return migration.Run(context.Stdout, c.dry)
}

func (c *migrateCmd) migrateImages() error {
	provisioner, _ := getProvisioner()
	if provisioner == "docker" {
		p, err := provision.Get(provisioner)
		if err != nil {
			return err
		}
		err = p.(provision.InitializableProvisioner).Initialize()
		if err != nil {
			return err
		}
		return docker.MigrateImages()
	}
	return nil
}

func (c *migrateCmd) migratePool() error {
	db, err := db.Conn()
	if err != nil {
		return err
	}
	defer db.Close()
	dbName, _ := config.GetString("database:name")
	fromColl := fmt.Sprintf("%s.docker_scheduler", dbName)
	toColl := fmt.Sprintf("%s.pool", dbName)
	session := db.Collection("docker_scheduler").Database.Session
	err = session.Run(bson.D{{"renameCollection", fromColl}, {"to", toColl}}, &bson.M{})
	if err != nil {
		return err
	}
	var apps []app.App
	err = db.Apps().Find().All(&apps)
	if err != nil {
		return err
	}
	for _, a := range apps {
		a.SetPool()
		err = db.Apps().Update(bson.M{"name": a.Name}, bson.M{"$set": bson.M{"pool": a.Pool}})
		if err != nil {
			return err
		}
	}
	return nil
}

func (c *migrateCmd) Flags() *gnuflag.FlagSet {
	if c.fs == nil {
		c.fs = gnuflag.NewFlagSet("migrate", gnuflag.ExitOnError)
		c.fs.BoolVar(&c.dry, "dry", false, "Do not run migrations, just print what would run")
		c.fs.BoolVar(&c.dry, "n", false, "Do not run migrations, just print what would run")
	}
	return c.fs
}
<commit_msg>cmd/tsr/migrate: fix test<commit_after>// Copyright 2015 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"

	"github.com/tsuru/config"
	"github.com/tsuru/tsuru/app"
	"github.com/tsuru/tsuru/cmd"
	"github.com/tsuru/tsuru/db"
	"github.com/tsuru/tsuru/migration"
	"github.com/tsuru/tsuru/provision"
	"github.com/tsuru/tsuru/provision/docker"
	"gopkg.in/mgo.v2/bson"
	"launchpad.net/gnuflag"
)

func getProvisioner() (string, error) {
	provisioner, err := config.GetString("provisioner")
	if provisioner == "" {
		provisioner = "docker"
	}
	return provisioner, err
}

type migrateCmd struct {
	fs  *gnuflag.FlagSet
	dry bool
}

func (*migrateCmd) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "migrate",
		Usage: "migrate",
		Desc:  "Runs migrations from previous versions of tsr",
	}
}

func (c *migrateCmd) Run(context *cmd.Context, client *cmd.Client) error {
	err := migration.Register("migrate-docker-images", c.migrateImages)
	if err != nil {
		return err
	}
	err = migration.Register("migrate-pool", c.migratePool)
	if err != nil {
		return err
	}
	return migration.Run(context.Stdout, c.dry)
}

func (c *migrateCmd) migrateImages() error {
	provisioner, _ := getProvisioner()
	if provisioner == "docker" {
		p, err := provision.Get(provisioner)
		if err != nil {
			return err
		}
		err = p.(provision.InitializableProvisioner).Initialize()
		if err != nil {
			return err
		}
		return docker.MigrateImages()
	}
	return nil
}

func (c *migrateCmd) migratePool() error {
	db, err := db.Conn()
	if err != nil {
		return err
	}
	defer db.Close()
	dbName, _ := config.GetString("database:name")
	fromColl := fmt.Sprintf("%s.docker_scheduler", dbName)
	toColl := fmt.Sprintf("%s.pool", dbName)
	session := db.Collection("docker_scheduler").Database.Session
	err = session.Run(bson.D{{"renameCollection", fromColl}, {"to", toColl}}, &bson.M{})
	if err != nil {
		return err
	}
	var apps []app.App
	err = db.Apps().Find(nil).All(&apps)
	if err != nil {
		return err
	}
	for _, a := range apps {
		a.SetPool()
		err = db.Apps().Update(bson.M{"name": a.Name}, bson.M{"$set": bson.M{"pool": a.Pool}})
		if err != nil {
			return err
		}
	}
	return nil
}

func (c *migrateCmd) Flags() *gnuflag.FlagSet {
	if c.fs == nil {
		c.fs = gnuflag.NewFlagSet("migrate", gnuflag.ExitOnError)
		c.fs.BoolVar(&c.dry, "dry", false, "Do not run migrations, just print what would run")
		c.fs.BoolVar(&c.dry, "n", false, "Do not run migrations, just print what would run")
	}
	return c.fs
}
<|endoftext|>


<commit_before>package linux

import (
	"bufio"
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

type Meminfo struct {
	MemTotal          uint64
	MemFree           uint64
	Buffers           uint64
	Cached            uint64
	SwapCached        uint64
	Active            uint64
	Inactive          uint64
	ActiveAnon        uint64
	InactiveAnon      uint64
	ActiveFile        uint64
	InactiveFile      uint64
	Unevictable       uint64
	Mlocked           uint64
	SwapTotal         uint64
	SwapFree          uint64
	Dirty             uint64
	Writeback         uint64
	AnonPages         uint64
	Mapped            uint64
	Shmem             uint64
	Slab              uint64
	SReclaimable      uint64
	SUnreclaim        uint64
	KernelStack       uint64
	PageTables        uint64
	NFS_Unstable      uint64
	Bounce            uint64
	WritebackTmp      uint64
	CommitLimit       uint64
	Committed_AS      uint64
	VmallocTotal      uint64
	VmallocUsed       uint64
	VmallocChunk      uint64
	HardwareCorrupted uint64
	AnonHugePages     uint64
	HugePages_Total   uint64
	HugePages_Free    uint64
	HugePages_Rsvd    uint64
	HugePages_Surp    uint64
	Hugepagesize      uint64
	DirectMap4k       uint64
	DirectMap2M       uint64
}

var procMeminfo = "/proc/meminfo"

func parseMeminfoLine(line string) (name string, val uint64, err error) {
	fields := strings.Fields(line)
	if len(fields) < 2 {
		err = fmt.Errorf("meminfo line needs at least two fields: %s", line)
		return
	}
	if len(fields[0]) < 2 {
		err = fmt.Errorf("meminfo field is too short: %s", fields[0])
		return
	}
	name = fields[0]
	name = name[0 : len(name)-1] // truncate last character
	if val, err = strconv.ParseUint(fields[1], 10, 64); err != nil {
		err = errors.New("could not parse stat line: " + err.Error())
		return
	}
	if len(fields) == 3 {
		switch fields[2] {
		case "kB":
			val = val * 1024
		default:
			err = fmt.Errorf("unexpected multiplier: %s", fields[2])
			return
		}
	}
	return
}

func ReadMeminfo() (meminfo Meminfo, err error) {
	file, err := os.Open(procMeminfo)
	if err != nil {
		return meminfo, err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	var name string
	var val uint64
	for i := 0; scanner.Scan(); i++ {
		if name, val, err = parseMeminfoLine(scanner.Text()); err != nil {
			return meminfo, err
		}
		switch name {

		case "MemTotal":
			meminfo.MemTotal = val
		case "MemFree":
			meminfo.MemFree = val
		case "Buffers":
			meminfo.Buffers = val
		case "Cached":
			meminfo.Cached = val
		case "SwapCached":
			meminfo.SwapCached = val
		case "Active":
			meminfo.Active = val
		case "Inactive":
			meminfo.Inactive = val
		case "Active(anon)":
			meminfo.ActiveAnon = val
		case "Inactive(anon)":
			meminfo.InactiveAnon = val
		case "Active(file)":
			meminfo.ActiveFile = val
		case "Inactive(file)":
			meminfo.InactiveFile = val
		case "Unevictable":
			meminfo.Unevictable = val
		case "Mlocked":
			meminfo.Mlocked = val
		case "SwapTotal":
			meminfo.SwapTotal = val
		case "SwapFree":
			meminfo.SwapFree = val
		case "Dirty":
			meminfo.Dirty = val
		case "Writeback":
			meminfo.Writeback = val
		case "AnonPages":
			meminfo.AnonPages = val
		case "Mapped":
			meminfo.Mapped = val
		case "Shmem":
			meminfo.Shmem = val
		case "Slab":
			meminfo.Slab = val
		case "SReclaimable":
			meminfo.SReclaimable = val
		case "SUnreclaim":
			meminfo.SUnreclaim = val
		case "KernelStack":
			meminfo.KernelStack = val
		case "PageTables":
			meminfo.PageTables = val
		case "NFS_Unstable":
			meminfo.NFS_Unstable = val
		case "Bounce":
			meminfo.Bounce = val
		case "WritebackTmp":
			meminfo.WritebackTmp = val
		case "CommitLimit":
			meminfo.CommitLimit = val
		case "Committed_AS":
			meminfo.Committed_AS = val
		case "VmallocTotal":
			meminfo.VmallocTotal = val
		case "VmallocUsed":
			meminfo.VmallocUsed = val
		case "VmallocChunk":
			meminfo.VmallocChunk = val
		case "HardwareCorrupted":
			meminfo.HardwareCorrupted = val
		case "AnonHugePages":
			meminfo.AnonHugePages = val
		case "HugePages_Total":
			meminfo.HugePages_Total = val
		case "HugePages_Free":
			meminfo.HugePages_Free = val
		case "HugePages_Rsvd":
			meminfo.HugePages_Rsvd = val
		case "HugePages_Surp":
			meminfo.HugePages_Surp = val
		case "Hugepagesize":
			meminfo.Hugepagesize = val
		case "DirectMap4k":
			meminfo.DirectMap4k = val
		case "DirectMap2M":
			meminfo.DirectMap2M = val
		default:
			log.Printf("ignoring unknown meminfo field %s", name)
		}
	}
	return
}
<commit_msg>add DirectMap1G to meminfo<commit_after>package linux

import (
	"bufio"
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

type Meminfo struct {
	MemTotal          uint64
	MemFree           uint64
	Buffers           uint64
	Cached            uint64
	SwapCached        uint64
	Active            uint64
	Inactive          uint64
	ActiveAnon        uint64
	InactiveAnon      uint64
	ActiveFile        uint64
	InactiveFile      uint64
	Unevictable       uint64
	Mlocked           uint64
	SwapTotal         uint64
	SwapFree          uint64
	Dirty             uint64
	Writeback         uint64
	AnonPages         uint64
	Mapped            uint64
	Shmem             uint64
	Slab              uint64
	SReclaimable      uint64
	SUnreclaim        uint64
	KernelStack       uint64
	PageTables        uint64
	NFS_Unstable      uint64
	Bounce            uint64
	WritebackTmp      uint64
	CommitLimit       uint64
	Committed_AS      uint64
	VmallocTotal      uint64
	VmallocUsed       uint64
	VmallocChunk      uint64
	HardwareCorrupted uint64
	AnonHugePages     uint64
	HugePages_Total   uint64
	HugePages_Free    uint64
	HugePages_Rsvd    uint64
	HugePages_Surp    uint64
	Hugepagesize      uint64
	DirectMap4k       uint64
	DirectMap2M       uint64
	DirectMap1G       uint64
}

var procMeminfo = "/proc/meminfo"

func parseMeminfoLine(line string) (name string, val uint64, err error) {
	fields := strings.Fields(line)
	if len(fields) < 2 {
		err = fmt.Errorf("meminfo line needs at least two fields: %s", line)
		return
	}
	if len(fields[0]) < 2 {
		err = fmt.Errorf("meminfo field is too short: %s", fields[0])
		return
	}
	name = fields[0]
	name = name[0 : len(name)-1] // truncate last character
	if val, err = strconv.ParseUint(fields[1], 10, 64); err != nil {
		err = errors.New("could not parse stat line: " + err.Error())
		return
	}
	if len(fields) == 3 {
		switch fields[2] {
		case "kB":
			val = val * 1024
		default:
			err = fmt.Errorf("unexpected multiplier: %s", fields[2])
			return
		}
	}
	return
}

func ReadMeminfo() (meminfo Meminfo, err error) {
	file, err := os.Open(procMeminfo)
	if err != nil {
		return meminfo, err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	var name string
	var val uint64
	for i := 0; scanner.Scan(); i++ {
		if name, val, err = parseMeminfoLine(scanner.Text()); err != nil {
			return meminfo, err
		}
		switch name {

		case "MemTotal":
			meminfo.MemTotal = val
		case "MemFree":
			meminfo.MemFree = val
		case "Buffers":
			meminfo.Buffers = val
		case "Cached":
			meminfo.Cached = val
		case "SwapCached":
			meminfo.SwapCached = val
		case "Active":
			meminfo.Active = val
		case "Inactive":
			meminfo.Inactive = val
		case "Active(anon)":
			meminfo.ActiveAnon = val
		case "Inactive(anon)":
			meminfo.InactiveAnon = val
		case "Active(file)":
			meminfo.ActiveFile = val
		case "Inactive(file)":
			meminfo.InactiveFile = val
		case "Unevictable":
			meminfo.Unevictable = val
		case "Mlocked":
			meminfo.Mlocked = val
		case "SwapTotal":
			meminfo.SwapTotal = val
		case "SwapFree":
			meminfo.SwapFree = val
		case "Dirty":
			meminfo.Dirty = val
		case "Writeback":
			meminfo.Writeback = val
		case "AnonPages":
			meminfo.AnonPages = val
		case "Mapped":
			meminfo.Mapped = val
		case "Shmem":
			meminfo.Shmem = val
		case "Slab":
			meminfo.Slab = val
		case "SReclaimable":
			meminfo.SReclaimable = val
		case "SUnreclaim":
			meminfo.SUnreclaim = val
		case "KernelStack":
			meminfo.KernelStack = val
		case "PageTables":
			meminfo.PageTables = val
		case "NFS_Unstable":
			meminfo.NFS_Unstable = val
		case "Bounce":
			meminfo.Bounce = val
		case "WritebackTmp":
			meminfo.WritebackTmp = val
		case "CommitLimit":
			meminfo.CommitLimit = val
		case "Committed_AS":
			meminfo.Committed_AS = val
		case "VmallocTotal":
			meminfo.VmallocTotal = val
		case "VmallocUsed":
			meminfo.VmallocUsed = val
		case "VmallocChunk":
			meminfo.VmallocChunk = val
		case "HardwareCorrupted":
			meminfo.HardwareCorrupted = val
		case "AnonHugePages":
			meminfo.AnonHugePages = val
		case "HugePages_Total":
			meminfo.HugePages_Total = val
		case "HugePages_Free":
			meminfo.HugePages_Free = val
		case "HugePages_Rsvd":
			meminfo.HugePages_Rsvd = val
		case "HugePages_Surp":
			meminfo.HugePages_Surp = val
		case "Hugepagesize":
			meminfo.Hugepagesize = val
		case "DirectMap4k":
			meminfo.DirectMap4k = val
		case "DirectMap2M":
			meminfo.DirectMap2M = val
		case "DirectMap1G":
			meminfo.DirectMap1G = val
		default:
			log.Printf("ignoring unknown meminfo field %s", name)
		}
	}
	return
}
<|endoftext|>


<commit_before>// A facebook graph api client in go.
// https://github.com/huandu/facebook/
//
// Copyright 2012-2014, Huan Du
// Licensed under the MIT license
// https://github.com/huandu/facebook/blob/master/LICENSE

// This is a Go library fully supports Facebook Graph API with file upload,
// batch request and FQL. It also supports Graph API 2.0 using the same methods.
//
// Library design is highly influenced by facebook official PHP/JS SDK.
// If you have used PHP/JS SDK before, it should look quite familiar.
//
// Here is a list of common scenarios to help you to get started.
//
// Scenario 1: Read a graph `user` object without access token.
//     res, _ := facebook.Get("/huandu", nil)
//     fmt.Println("my facebook id is", res["id"])
//
// Scenario 2: Read a graph `user` object with a valid access token.
//     res, _ := facebook.Get("/me/feed", facebook.Params{
//          "access_token": "a-valid-access-token",
//     })
//
//     // read my last feed.
//     fmt.Println("my latest feed story is:", res.Get("data.0.story"))
//
// Scenario 3: Use App and Session struct. It's recommended to use them
// in a production app.
//     // create a global App var to hold your app id and secret.
//     var globalApp = facebook.New("your-app-id", "your-app-secret")
//
//     // facebook asks for a valid redirect uri when parsing signed request.
//     // it's a new enforced policy starting in late 2013.
//     // it can be omitted in a mobile app server.
//     globalApp.RedirectUri = "http://your-site-canvas-url/"
//
//     // here comes a client with a facebook signed request string in query string.
//     // creates a new session with signed request.
//     session, _ := globalApp.SessionFromSignedRequest(signedRequest)
//
//     // or, you just get a valid access token in other way.
//     // creates a session directly.
//     seesion := globalApp.Session(token)
//
//     // use session to send api request with your access token.
//     res, _ := session.Get("/me/feed", nil)
//
//     // validate access token. err is nil if token is valid.
//     err := session.Validate()
//
// Scenario 4: Read graph api response and decode result into a struct.
// Struct tag definition is compatible with the definition in `encoding/json`.
//     // define a facebook feed object.
//     type FacebookFeed struct {
//         Id string `facebook:",required"` // must exist
//         Story string
//         From *FacebookFeedFrom
//         CreatedTime string `facebook:"created_time"` // use customized field name
//     }
//
//     type FacebookFeedFrom struct {
//         Name, Id string
//     }
//
//     // create a feed object direct from graph api result.
//     var feed FacebookFeed
//     res, _ := session.Get("/me/feed", nil)
//     res.DecodeField("data.0", &feed) // read latest feed
//
// Scenario 5: Send a batch request.
//     params1 := Params{
//         "method": facebook.GET,
//         "relative_url": "huandu",
//     }
//     params2 := Params{
//         "method": facebook.GET,
//         "relative_url": uint64(100002828925788),
//     }
//     res, err := facebook.BatchApi(your_access_token, params1, params2)
//     // res is a []Result. if err is nil, res[0] and res[1] are response to
//     // params1 and params2 respectively.
//
// Scenario 6: Use it in Google App Engine with `appengine/urlfetch` package.
//     import (
//         "appengine"
//         "appengine/urlfetch"
//     )
//
//     // suppose it's the appengine context initialized somewhere.
//     var context appengine.Context
//
//     // default Session object uses http.DefaultClient which is not supported
//     // by appengine. we have to create a Session and assign it a special client.
//     seesion := globalApp.Session("a-access-token")
//     session.HttpClient = urlfetch.Client(context)
//
//     // now, session uses appengine http client now.
//     res, err := session.Get("/me", nil)
//
// Scenario 7: Select Graph API version. See https://developers.facebook.com/docs/apps/versions .
//     // this library uses default version by default.
//     // change following global variable to specific a global default version.
//     Version = "v2.0"

//     // now you will get an error as v2.0 api doesn't allow you to do so.
//     Api("huan.du", GET, nil)
//
//     // you can also specify version per session.
//     session := &Session{}
//     session.Version = "v2.0" // overwrite global default.
//
// I've try my best to add enough information in every public method and type.
// If you still have any question or suggestion, feel free to create an issue
// or send pull request to me. Thank you.
//
// This library doesn't implement any deprecated old RESTful API. And it won't.
package facebook

var (
    // Default facebook api version.
    // It can be "v1.0" or "v2.0" or empty per facebook current document.
    // See https://developers.facebook.com/docs/apps/versions for details.
    Version string
)

// Makes a facebook graph api call.
//
// Method can be GET, POST, DELETE or PUT.
//
// Params represents query strings in this call.
// Keys and values in params will be encoded for URL automatically. So there is
// no need to encode keys or values in params manually. Params can be nil.
//
// If you want to get
//     https://graph.facebook.com/huandu?fields=name,username
// Api should be called as following
//     Api("/huandu", GET, Params{"fields": "name,username"})
// or in a simplified way
//     Get("/huandu", Params{"fields": "name,username"})
//
// Api is a wrapper of Session.Api(). It's designed for graph api that doesn't require
// app id, app secret and access token. It can be called in multiple goroutines.
//
// If app id, app secret or access token is required in graph api, caller should
// create a new facebook session through App instance instead.
func Api(path string, method Method, params Params) (Result, error) {
    return defaultSession.Api(path, method, params)
}

// Get is a short hand of Api(path, GET, params).
func Get(path string, params Params) (Result, error) {
    return Api(path, GET, params)
}

// Post is a short hand of Api(path, POST, params).
func Post(path string, params Params) (Result, error) {
    return Api(path, POST, params)
}

// Delete is a short hand of Api(path, DELETE, params).
func Delete(path string, params Params) (Result, error) {
    return Api(path, DELETE, params)
}

// Put is a short hand of Api(path, PUT, params).
func Put(path string, params Params) (Result, error) {
    return Api(path, PUT, params)
}

// Makes a batch facebook graph api call.
//
// BatchApi supports most kinds of batch calls defines in facebook batch api document,
// except uploading binary data. Use Batch to do so.
//
// See https://developers.facebook.com/docs/reference/api/batch/ to learn more about Batch Requests.
func BatchApi(accessToken string, params ...Params) ([]Result, error) {
    return Batch(Params{"access_token": accessToken}, params...)
}

// Makes a batch facebook graph api call.
// Batch is designed for more advanced usage including uploading binary files.
//
// An uploading files sample
//     // equivalent to following curl command (borrowed from facebook docs)
//     //     curl \
//     //         -F 'access_token=…' \
//     //         -F 'batch=[{"method":"POST","relative_url":"me/photos","body":"message=My cat photo","attached_files":"file1"},{"method":"POST","relative_url":"me/photos","body":"message=My dog photo","attached_files":"file2"},]' \
//     //         -F 'file1=@cat.gif' \
//     //         -F 'file2=@dog.jpg' \
//     //         https://graph.facebook.com
//     Batch(Params{
//         "access_token": "the-access-token",
//         "file1": File("cat.gif"),
//         "file2": File("dog.jpg"),
//     }, Params{
//         "method": "POST",
//         "relative_url": "me/photos",
//         "body": "message=My cat photo",
//         "attached_files": "file1",
//     }, Params{
//         "method": "POST",
//         "relative_url": "me/photos",
//         "body": "message=My dog photo",
//         "attached_files": "file2",
//     })
//
// See https://developers.facebook.com/docs/reference/api/batch/ to learn more about Batch Requests.
func Batch(batchParams Params, params ...Params) ([]Result, error) {
    return defaultSession.Batch(batchParams, params...)
}
<commit_msg>fix a doc typo.<commit_after>// A facebook graph api client in go.
// https://github.com/huandu/facebook/
//
// Copyright 2012-2014, Huan Du
// Licensed under the MIT license
// https://github.com/huandu/facebook/blob/master/LICENSE

// This is a Go library fully supports Facebook Graph API with file upload,
// batch request and FQL. It also supports Graph API 2.0 using the same methods.
//
// Library design is highly influenced by facebook official PHP/JS SDK.
// If you have used PHP/JS SDK before, it should look quite familiar.
//
// Here is a list of common scenarios to help you to get started.
//
// Scenario 1: Read a graph `user` object without access token.
//     res, _ := facebook.Get("/huandu", nil)
//     fmt.Println("my facebook id is", res["id"])
//
// Scenario 2: Read a graph `user` object with a valid access token.
//     res, _ := facebook.Get("/me/feed", facebook.Params{
//          "access_token": "a-valid-access-token",
//     })
//
//     // read my last feed.
//     fmt.Println("my latest feed story is:", res.Get("data.0.story"))
//
// Scenario 3: Use App and Session struct. It's recommended to use them
// in a production app.
//     // create a global App var to hold your app id and secret.
//     var globalApp = facebook.New("your-app-id", "your-app-secret")
//
//     // facebook asks for a valid redirect uri when parsing signed request.
//     // it's a new enforced policy starting in late 2013.
//     // it can be omitted in a mobile app server.
//     globalApp.RedirectUri = "http://your-site-canvas-url/"
//
//     // here comes a client with a facebook signed request string in query string.
//     // creates a new session with signed request.
//     session, _ := globalApp.SessionFromSignedRequest(signedRequest)
//
//     // or, you just get a valid access token in other way.
//     // creates a session directly.
//     seesion := globalApp.Session(token)
//
//     // use session to send api request with your access token.
//     res, _ := session.Get("/me/feed", nil)
//
//     // validate access token. err is nil if token is valid.
//     err := session.Validate()
//
// Scenario 4: Read graph api response and decode result into a struct.
// Struct tag definition is compatible with the definition in `encoding/json`.
//     // define a facebook feed object.
//     type FacebookFeed struct {
//         Id string `facebook:",required"` // must exist
//         Story string
//         From *FacebookFeedFrom
//         CreatedTime string `facebook:"created_time"` // use customized field name
//     }
//
//     type FacebookFeedFrom struct {
//         Name, Id string
//     }
//
//     // create a feed object direct from graph api result.
//     var feed FacebookFeed
//     res, _ := session.Get("/me/feed", nil)
//     res.DecodeField("data.0", &feed) // read latest feed
//
// Scenario 5: Send a batch request.
//     params1 := Params{
//         "method": facebook.GET,
//         "relative_url": "huandu",
//     }
//     params2 := Params{
//         "method": facebook.GET,
//         "relative_url": uint64(100002828925788),
//     }
//     res, err := facebook.BatchApi(your_access_token, params1, params2)
//     // res is a []Result. if err is nil, res[0] and res[1] are response to
//     // params1 and params2 respectively.
//
// Scenario 6: Use it in Google App Engine with `appengine/urlfetch` package.
//     import (
//         "appengine"
//         "appengine/urlfetch"
//     )
//
//     // suppose it's the appengine context initialized somewhere.
//     var context appengine.Context
//
//     // default Session object uses http.DefaultClient which is not supported
//     // by appengine. we have to create a Session and assign it a special client.
//     seesion := globalApp.Session("a-access-token")
//     session.HttpClient = urlfetch.Client(context)
//
//     // now, session uses appengine http client now.
//     res, err := session.Get("/me", nil)
//
// Scenario 7: Select Graph API version. See https://developers.facebook.com/docs/apps/versions .
//     // this library uses default version by default.
//     // change following global variable to specific a global default version.
//     Version = "v2.0"
//
//     // now you will get an error as v2.0 api doesn't allow you to do so.
//     Api("huan.du", GET, nil)
//
//     // you can also specify version per session.
//     session := &Session{}
//     session.Version = "v2.0" // overwrite global default.
//
// I've try my best to add enough information in every public method and type.
// If you still have any question or suggestion, feel free to create an issue
// or send pull request to me. Thank you.
//
// This library doesn't implement any deprecated old RESTful API. And it won't.
package facebook

var (
    // Default facebook api version.
    // It can be "v1.0" or "v2.0" or empty per facebook current document.
    // See https://developers.facebook.com/docs/apps/versions for details.
    Version string
)

// Makes a facebook graph api call.
//
// Method can be GET, POST, DELETE or PUT.
//
// Params represents query strings in this call.
// Keys and values in params will be encoded for URL automatically. So there is
// no need to encode keys or values in params manually. Params can be nil.
//
// If you want to get
//     https://graph.facebook.com/huandu?fields=name,username
// Api should be called as following
//     Api("/huandu", GET, Params{"fields": "name,username"})
// or in a simplified way
//     Get("/huandu", Params{"fields": "name,username"})
//
// Api is a wrapper of Session.Api(). It's designed for graph api that doesn't require
// app id, app secret and access token. It can be called in multiple goroutines.
//
// If app id, app secret or access token is required in graph api, caller should
// create a new facebook session through App instance instead.
func Api(path string, method Method, params Params) (Result, error) {
    return defaultSession.Api(path, method, params)
}

// Get is a short hand of Api(path, GET, params).
func Get(path string, params Params) (Result, error) {
    return Api(path, GET, params)
}

// Post is a short hand of Api(path, POST, params).
func Post(path string, params Params) (Result, error) {
    return Api(path, POST, params)
}

// Delete is a short hand of Api(path, DELETE, params).
func Delete(path string, params Params) (Result, error) {
    return Api(path, DELETE, params)
}

// Put is a short hand of Api(path, PUT, params).
func Put(path string, params Params) (Result, error) {
    return Api(path, PUT, params)
}

// Makes a batch facebook graph api call.
//
// BatchApi supports most kinds of batch calls defines in facebook batch api document,
// except uploading binary data. Use Batch to do so.
//
// See https://developers.facebook.com/docs/reference/api/batch/ to learn more about Batch Requests.
func BatchApi(accessToken string, params ...Params) ([]Result, error) {
    return Batch(Params{"access_token": accessToken}, params...)
}

// Makes a batch facebook graph api call.
// Batch is designed for more advanced usage including uploading binary files.
//
// An uploading files sample
//     // equivalent to following curl command (borrowed from facebook docs)
//     //     curl \
//     //         -F 'access_token=…' \
//     //         -F 'batch=[{"method":"POST","relative_url":"me/photos","body":"message=My cat photo","attached_files":"file1"},{"method":"POST","relative_url":"me/photos","body":"message=My dog photo","attached_files":"file2"},]' \
//     //         -F 'file1=@cat.gif' \
//     //         -F 'file2=@dog.jpg' \
//     //         https://graph.facebook.com
//     Batch(Params{
//         "access_token": "the-access-token",
//         "file1": File("cat.gif"),
//         "file2": File("dog.jpg"),
//     }, Params{
//         "method": "POST",
//         "relative_url": "me/photos",
//         "body": "message=My cat photo",
//         "attached_files": "file1",
//     }, Params{
//         "method": "POST",
//         "relative_url": "me/photos",
//         "body": "message=My dog photo",
//         "attached_files": "file2",
//     })
//
// See https://developers.facebook.com/docs/reference/api/batch/ to learn more about Batch Requests.
func Batch(batchParams Params, params ...Params) ([]Result, error) {
    return defaultSession.Batch(batchParams, params...)
}
<|endoftext|>


<commit_before>package chaining

import "jecolasurdo/go-chaining/injectionbehavior"
import "errors"

// Flush returns the context's error and final result, and resets the context back to its default state.
func (c *Context) Flush() (interface{}, error) {
	localError := c.LocalError
	finalResult := c.PreviousActionResult
	c.LocalError = nil
	c.PreviousActionResult = nil
	return finalResult, localError
}

// ApplyNullary executes an action which takes no arguments and returns only an error.
//
// Since the supplied action returns no value aside from an error, the context will supply nil as a pseudo-result
// for the supplied action. The context will then apply that nil to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
func (c *Context) ApplyNullary(action func() error) {
	if c.LocalError == nil {
		c.LocalError = action()
	}
}

// ApplyNullaryIface executes an action which takes no arguments and returns a tuple of (interface{}, error).
//
// The context will apply the supplied action's interface{} result to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
func (c *Context) ApplyNullaryIface(action func() (interface{}, error), behavior injectionbehavior.InjectionBehavior) {
	restatedAction := func(val interface{}) (interface{}, error) {
		return action()
	}
	c.ApplyUnaryIface(restatedAction, ActionArg{Behavior: behavior})
}

// ApplyUnary executes an action which takes one argument returns only an error.
//
// The single interface{} argument accepted by the action can be supplied via the arg parameter.
//
// Since the supplied action returns no value aside from an error, the context will supply nil as a pseudo-result
// for the supplied action. The context will then apply that nil to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
func (c *Context) ApplyUnary(action func(interface{}) error, arg ActionArg) {
	c.LocalError = errors.New("ApplyUnary not implemented")
	c.PreviousActionResult = nil
}

// ApplyUnaryIface executes an action which takes one argument, and returns a tuple of (interface{}, error).
//
// The single interface{} argument accepted by the action can be supplied via the arg parameter.
//
// The context will apply the supplied action's interface{} result to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
func (c *Context) ApplyUnaryIface(action func(interface{}) (interface{}, error), arg ActionArg) {
	if c.LocalError != nil {
		return
	}
	var valueToInject interface{}
	if arg.Behavior == injectionbehavior.InjectSuppliedValue {
		valueToInject = arg.Value
	} else {
		valueToInject = c.PreviousActionResult
	}
	result, err := action(valueToInject)
	c.LocalError = err
	c.PreviousActionResult = result
}

// ApplyNullaryBool executes an action which takes no arguments and returns a tuple of (bool, error).
//
// The context will apply the supplied action's bool result to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
//
// In addition to threading the (bool, error) tuple into the current context, NullaryBool itself also returns a bool.
// This is useful for inlining the method in boolean statements.
func (c *Context) ApplyNullaryBool(action func() (bool, error)) bool {
	if c.LocalError != nil {
		return false
	}

	result, err := action()
	c.LocalError = err
	return result
}

// ApplyUnaryBool executes an action which takes one argument and returns a tuple of (bool, error).
//
// The single interface{} argument accepted by the action can be supplied via the arg parameter.
//
// The context will apply the supplied action's bool result to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
//
// In addition to threading the (bool, error) tuple into the current context, UnaryBool itself also returns a bool.
// This is useful for inlining the method in boolean statements.
func (c *Context) ApplyUnaryBool(action func(interface{}) (bool, error), arg ActionArg) bool {
	restatedAction := func(val interface{}) (interface{}, error) {
		return action(val)
	}
	c.ApplyUnaryIface(restatedAction, arg)
	return c.PreviousActionResult.(bool)
}
<commit_msg>Stated ApplyUnary in terms of ApplyUnaryIface<commit_after>package chaining

import "jecolasurdo/go-chaining/injectionbehavior"

// Flush returns the context's error and final result, and resets the context back to its default state.
func (c *Context) Flush() (interface{}, error) {
	localError := c.LocalError
	finalResult := c.PreviousActionResult
	c.LocalError = nil
	c.PreviousActionResult = nil
	return finalResult, localError
}

// ApplyNullary executes an action which takes no arguments and returns only an error.
//
// Since the supplied action returns no value aside from an error, the context will supply nil as a pseudo-result
// for the supplied action. The context will then apply that nil to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
func (c *Context) ApplyNullary(action func() error) {
	if c.LocalError == nil {
		c.LocalError = action()
	}
}

// ApplyNullaryIface executes an action which takes no arguments and returns a tuple of (interface{}, error).
//
// The context will apply the supplied action's interface{} result to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
func (c *Context) ApplyNullaryIface(action func() (interface{}, error), behavior injectionbehavior.InjectionBehavior) {
	restatedAction := func(val interface{}) (interface{}, error) {
		return action()
	}
	c.ApplyUnaryIface(restatedAction, ActionArg{Behavior: behavior})
}

// ApplyUnary executes an action which takes one argument returns only an error.
//
// The single interface{} argument accepted by the action can be supplied via the arg parameter.
//
// Since the supplied action returns no value aside from an error, the context will supply nil as a pseudo-result
// for the supplied action. The context will then apply that nil to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
func (c *Context) ApplyUnary(action func(interface{}) error, arg ActionArg) {
	restatedAction := func(val interface{}) (interface{}, error) {
		err := action(val)
		return nil, err
	}
	c.ApplyUnaryIface(restatedAction, arg)
}

// ApplyUnaryIface executes an action which takes one argument, and returns a tuple of (interface{}, error).
//
// The single interface{} argument accepted by the action can be supplied via the arg parameter.
//
// The context will apply the supplied action's interface{} result to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
func (c *Context) ApplyUnaryIface(action func(interface{}) (interface{}, error), arg ActionArg) {
	if c.LocalError != nil {
		return
	}
	var valueToInject interface{}
	if arg.Behavior == injectionbehavior.InjectSuppliedValue {
		valueToInject = arg.Value
	} else {
		valueToInject = c.PreviousActionResult
	}
	result, err := action(valueToInject)
	c.LocalError = err
	c.PreviousActionResult = result
}

// ApplyNullaryBool executes an action which takes no arguments and returns a tuple of (bool, error).
//
// The context will apply the supplied action's bool result to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
//
// In addition to threading the (bool, error) tuple into the current context, NullaryBool itself also returns a bool.
// This is useful for inlining the method in boolean statements.
func (c *Context) ApplyNullaryBool(action func() (bool, error)) bool {
	if c.LocalError != nil {
		return false
	}

	result, err := action()
	c.LocalError = err
	return result
}

// ApplyUnaryBool executes an action which takes one argument and returns a tuple of (bool, error).
//
// The single interface{} argument accepted by the action can be supplied via the arg parameter.
//
// The context will apply the supplied action's bool result to the next action called within the context,
// unless the override behavior for the next action dictates otherwise.
//
// The error returned by the supplied action is also applied to the current context.
// If error is not nil, subsequent actions executed within the same context will be ignored.
//
// In addition to threading the (bool, error) tuple into the current context, UnaryBool itself also returns a bool.
// This is useful for inlining the method in boolean statements.
func (c *Context) ApplyUnaryBool(action func(interface{}) (bool, error), arg ActionArg) bool {
	restatedAction := func(val interface{}) (interface{}, error) {
		return action(val)
	}
	c.ApplyUnaryIface(restatedAction, arg)
	return c.PreviousActionResult.(bool)
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"errors"
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"time"
)

const (
	pubLen int = 12
)

func checkOTP(w http.ResponseWriter, r *http.Request, dal *Dal) {
	if r.URL.Query()["otp"] == nil || r.URL.Query()["nonce"] == nil || r.URL.Query()["id"] == nil {
		reply(w, "", "", MISSING_PARAMETER, "", dal)
		return
	}
	otp := r.URL.Query()["otp"][0]
	nonce := r.URL.Query()["nonce"][0]
	id := r.URL.Query()["id"][0]
	if len(otp) < pubLen {
		reply(w, otp, nonce, BAD_OTP, id, dal)
		return
	}
	pub := otp[:pubLen]

	k, err := dal.GetKey(pub)
	if err != nil {
		reply(w, otp, nonce, BAD_OTP, id, dal)
		return
	} else {
		k, err = Gate(k, otp)
		if err != nil {
			reply(w, otp, nonce, err.Error(), id, dal)
			return
		} else {
			err = dal.UpdateKey(k)
			if err != nil {
				log.Println("fail to update key counter/session")
				return
			}
			reply(w, otp, nonce, OK, id, dal)
			return
		}
	}
}

func Sign(values []string, key []byte) []byte {
	payload := ""
	for _, v := range values {
		payload += v + "&"
	}
	payload = payload[:len(payload)-1]

	mac := hmac.New(sha1.New, key)
	mac.Write([]byte(payload))
	return mac.Sum(nil)
}

func loadKey(id string, dal *Dal) ([]byte, error) {
	i, err := dal.GetApp(id)
	if err != nil {
		return []byte{}, errors.New(NO_SUCH_CLIENT)
	}

	return i, nil
}

func reply(w http.ResponseWriter, otp, nonce, status, id string, dal *Dal) {
	values := []string{}
	key := []byte{}
	err := errors.New("")

	values = append(values, "nonce="+nonce)
	values = append(values, "otp="+otp)
	if status != MISSING_PARAMETER {
		key, err = loadKey(id, dal)
		if err == nil {
			values = append(values, "status="+status)
		} else {
			values = append(values, "status="+err.Error())
		}
	} else {
		values = append(values, "status="+status)
	}
	values = append(values, "t="+time.Now().Format(time.RFC3339))
	if status != MISSING_PARAMETER {
		values = append(values, "h="+base64.StdEncoding.EncodeToString(Sign(values, key)))
	}

	ret := ""
	for _, v := range values {
		ret += v + "\n"
	}

	w.Write([]byte(ret))
}

func runAPI(dal *Dal, port string) {
	r := mux.NewRouter()

	r.HandleFunc("/wsapi/2.0/verify", func(w http.ResponseWriter, r *http.Request) {
		checkOTP(w, r, dal)
	}).Methods("GET")

	http.Handle("/", r)
	log.Println("Listening on port " + port + "...")
	http.ListenAndServe(":"+port, nil)
}
<commit_msg>including the key name in the response (for an eventual comparison)<commit_after>package main

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"errors"
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"time"
)

const (
	pubLen int = 12
)

func checkOTP(w http.ResponseWriter, r *http.Request, dal *Dal) {
	if r.URL.Query()["otp"] == nil || r.URL.Query()["nonce"] == nil || r.URL.Query()["id"] == nil {
		reply(w, "", "", "", MISSING_PARAMETER, "", dal)
		return
	}
	otp := r.URL.Query()["otp"][0]
	nonce := r.URL.Query()["nonce"][0]
	id := r.URL.Query()["id"][0]
	name := ""

	if len(otp) < pubLen {
		reply(w, otp, name, nonce, BAD_OTP, id, dal)
		return
	}
	pub := otp[:pubLen]

	k, err := dal.GetKey(pub)
	if err != nil {
		reply(w, otp, name, nonce, BAD_OTP, id, dal)
		return
	} else {
		k, err = Gate(k, otp)
		if err != nil {
			reply(w, otp, name, nonce, err.Error(), id, dal)
			return
		} else {
			err = dal.UpdateKey(k)
			if err != nil {
				log.Println("fail to update key counter/session")
				return
			}

			name := k.Name
			reply(w, otp, name, nonce, OK, id, dal)
			return
		}
	}
}

func Sign(values []string, key []byte) []byte {
	payload := ""
	for _, v := range values {
		payload += v + "&"
	}
	payload = payload[:len(payload)-1]

	mac := hmac.New(sha1.New, key)
	mac.Write([]byte(payload))
	return mac.Sum(nil)
}

func loadKey(id string, dal *Dal) ([]byte, error) {
	i, err := dal.GetApp(id)
	if err != nil {
		return []byte{}, errors.New(NO_SUCH_CLIENT)
	}

	return i, nil
}

func reply(w http.ResponseWriter, otp, name, nonce, status, id string, dal *Dal) {
	values := []string{}
	key := []byte{}
	err := errors.New("")

	values = append(values, "nonce="+nonce)
	values = append(values, "otp="+otp)
	if status != MISSING_PARAMETER {
		key, err = loadKey(id, dal)
		if err == nil {
			values = append(values, "name="+name)
			values = append(values, "status="+status)
		} else {
			values = append(values, "status="+err.Error())
		}
	} else {
		values = append(values, "status="+status)
	}
	values = append(values, "t="+time.Now().Format(time.RFC3339))
	if status != MISSING_PARAMETER {
		values = append(values, "h="+base64.StdEncoding.EncodeToString(Sign(values, key)))
	}

	ret := ""
	for _, v := range values {
		ret += v + "\n"
	}

	w.Write([]byte(ret))
}

func runAPI(dal *Dal, port string) {
	r := mux.NewRouter()

	r.HandleFunc("/wsapi/2.0/verify", func(w http.ResponseWriter, r *http.Request) {
		checkOTP(w, r, dal)
	}).Methods("GET")

	http.Handle("/", r)
	log.Println("Listening on port " + port + "...")
	http.ListenAndServe(":"+port, nil)
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/labstack/echo"
	"net/http"
	"strconv"
	"fmt"
)

// api

// отправляет json-ответ с массивом текущих ботов
func listBot(c *echo.Context) error {
	//	TODO сформировать список ботов и отправить клиенту
	// временные данные
	list, err := MB.GetListBots()
	if err != nil {
		return c.JSON(http.StatusConflict, nil)
	}
	return c.JSON(http.StatusOK, list)
}

func createBot(c *echo.Context) error {
	//	TODO создать нового бота
	return c.String(http.StatusOK, "ok\n")
}

// sendActionToBot отправить команду боту
func sendActionToBot(c *echo.Context) error {
	param := make(map[string]interface{})
	id := c.Param("id")			// распарсить и получить id
	action := c.Param("action")	// и команду

	switch action {
	case "update":
		ProcessID, _ := strconv.Atoi(c.Query("ProcessID"))
		param["ProcessID"] = ProcessID
	case "connect":
		infbot := make(map[string]string)
		infbot["name"] = "bot1"
		id, _ = MB.AddBot(infbot)
	case "disconnect":
//		TODO отключить бота от игрового клиента
	}

	err := MB.SendActionToBot(id, action, param)	// отправить команду боту
	if err != nil {
		fmt.Println(err)
	}

	return c.String(http.StatusOK, "ok\n")
}
func deleteBot(c *echo.Context) error {
	//	TODO удалить бота
	return c.String(http.StatusOK, "ok\n")
}
<commit_msg>В функции createBot TODO заменен на код:   1. получить данные от веб-клиента   2. передать данные менеджеру ботов и создать новый экземпляр бота   3. вернуть веб-клиенту сообщение, что команда выполнена.<commit_after>package main

import (
	"github.com/labstack/echo"
	"net/http"
	"strconv"
	"fmt"
)

// api

// отправляет json-ответ с массивом текущих ботов
func listBot(c *echo.Context) error {
	//	TODO сформировать список ботов и отправить клиенту
	// временные данные
	list, err := MB.GetListBots()
	if err != nil {
		return c.JSON(http.StatusConflict, nil)
	}
	return c.JSON(http.StatusOK, list)
}

func createBot(c *echo.Context) error {
	infbot := make(map[string]string)
	infbot["name"] = c.Query("name")
	infbot["server"] = c.Query("server")
	infbot["login"] = c.Query("login")
	infbot["password"] = c .Query("password")
	id, err := MB.AddBot(infbot)
	if err != nil {
		fmt.Println(err)
	}
	return c.String(http.StatusOK, id)
}

// sendActionToBot отправить команду боту
func sendActionToBot(c *echo.Context) error {
	param := make(map[string]interface{})
	id := c.Param("id")			// распарсить и получить id
	action := c.Param("action")	// и команду

	switch action {
	case "update":
		ProcessID, _ := strconv.Atoi(c.Query("ProcessID"))
		param["ProcessID"] = ProcessID
	case "connect":
		infbot := make(map[string]string)
		infbot["name"] = "bot1"
		id, _ = MB.AddBot(infbot)
	case "disconnect":
//		TODO отключить бота от игрового клиента
	}

	err := MB.SendActionToBot(id, action, param)	// отправить команду боту
	if err != nil {
		fmt.Println(err)
	}

	return c.String(http.StatusOK, "ok\n")
}
func deleteBot(c *echo.Context) error {
	//	TODO удалить бота
	return c.String(http.StatusOK, "ok\n")
}
<|endoftext|>


<commit_before>// Copyright © 2015 Hraban Luyat <hraban@0brg.net>
//
// License for use of this code is detailed in the LICENSE file

package opus

import (
	"fmt"
	"unsafe"
)

/*
// Statically link libopus. Requires a libopus.a in every directory you use this
// as a dependency in. Not great, but CGO doesn't offer anything better, right
// now. Unless you require everyone who USES this package to have libopus
// installed system-wide, which is more of a chore because it's so new. Everyone
// will end up having to build it from source anyway, might as well just dump
// the pre-built lib in here. At least it will be up to the package maintainer,
// not the user.
//
// If I missed something, and somebody knows a better way: please let me know.
#cgo LDFLAGS: libopus.a -lm
#cgo CFLAGS: -std=c99 -Wall -Werror -pedantic -Ilibopusbuild/include
#include <opus/opus.h>
*/
import "C"

type Application int

// These constants should be taken from the library instead of defined here.
// Unfortunatly, they are #defines, and CGO can't import those.
const (
	// Optimize encoding for VOIP
	APPLICATION_VOIP Application = 2048
	// Optimize encoding for non-voice signals like music
	APPLICATION_AUDIO Application = 2049
	// Optimize encoding for low latency applications
	APPLICATION_RESTRICTED_LOWDELAY Application = 2051
)

const (
	xMAX_BITRATE       = 48000
	xMAX_FRAME_SIZE_MS = 60
	xMAX_FRAME_SIZE    = xMAX_BITRATE * xMAX_FRAME_SIZE_MS / 1000
)

func Version() string {
	return C.GoString(C.opus_get_version_string())
}

type Encoder struct {
	p *C.struct_OpusEncoder
}

func opuserr(code int) error {
	return fmt.Errorf("opus: %s", C.GoString(C.opus_strerror(C.int(code))))
}

func NewEncoder(sample_rate int, channels int, application Application) (*Encoder, error) {
	var errno int
	p := C.opus_encoder_create(C.opus_int32(sample_rate), C.int(channels), C.int(application), (*C.int)(unsafe.Pointer(&errno)))
	if errno != 0 {
		return nil, opuserr(errno)
	}
	return &Encoder{p: p}, nil
}

func (enc *Encoder) EncodeFloat32(pcm []float32) ([]byte, error) {
	if pcm == nil || len(pcm) == 0 {
		return nil, fmt.Errorf("opus: no data supplied")
	}
	// I never know how much to allocate
	data := make([]byte, 10000)
	n := int(C.opus_encode_float(
		enc.p,
		(*C.float)(&pcm[0]),
		C.int(len(pcm)),
		(*C.uchar)(&data[0]),
		C.opus_int32(cap(data))))
	if n < 0 {
		return nil, opuserr(n)
	}
	return data[:n], nil
}

// Returns an error if the encoder was already closed
func (enc *Encoder) Close() error {
	if enc.p == nil {
		return fmt.Errorf("opus: encoder already closed")
	}
	C.opus_encoder_destroy(enc.p)
	enc.p = nil
	return nil
}

type Decoder struct {
	p           *C.struct_OpusDecoder
	sample_rate int
}

func NewDecoder(sample_rate int, channels int) (*Decoder, error) {
	var errno int
	p := C.opus_decoder_create(C.opus_int32(sample_rate), C.int(channels), (*C.int)(unsafe.Pointer(&errno)))
	if errno != 0 {
		return nil, opuserr(errno)
	}
	dec := &Decoder{
		p:           p,
		sample_rate: sample_rate,
	}
	return dec, nil
}

func (dec *Decoder) DecodeFloat32(data []byte) ([]float32, error) {
	if data == nil || len(data) == 0 {
		return nil, fmt.Errorf("opus: no data supplied")
	}
	// I don't know how big this frame will be, but this is the limit
	pcm := make([]float32, xMAX_FRAME_SIZE_MS*dec.sample_rate/1000)
	n := int(C.opus_decode_float(
		dec.p,
		(*C.uchar)(&data[0]),
		C.opus_int32(len(data)),
		(*C.float)(&pcm[0]),
		C.int(cap(pcm)),
		0))
	if n < 0 {
		return nil, opuserr(n)
	}
	return pcm[:n], nil
}

// Returns an error if the encoder was already closed
func (dec *Decoder) Close() error {
	if dec.p == nil {
		return fmt.Errorf("opus: decoder already closed")
	}
	C.opus_decoder_destroy(dec.p)
	dec.p = nil
	return nil
}
<commit_msg>Update dependency build directory for cgo<commit_after>// Copyright © 2015 Hraban Luyat <hraban@0brg.net>
//
// License for use of this code is detailed in the LICENSE file

package opus

import (
	"fmt"
	"unsafe"
)

/*
// Statically link libopus. Requires a libopus.a in every directory you use this
// as a dependency in. Not great, but CGO doesn't offer anything better, right
// now. Unless you require everyone who USES this package to have libopus
// installed system-wide, which is more of a chore because it's so new. Everyone
// will end up having to build it from source anyway, might as well just dump
// the pre-built lib in here. At least it will be up to the package maintainer,
// not the user.
//
// If I missed something, and somebody knows a better way: please let me know.
#cgo LDFLAGS: libopus.a -lm
#cgo CFLAGS: -std=c99 -Wall -Werror -pedantic -Ibuild/include
#include <opus/opus.h>
*/
import "C"

type Application int

// These constants should be taken from the library instead of defined here.
// Unfortunatly, they are #defines, and CGO can't import those.
const (
	// Optimize encoding for VOIP
	APPLICATION_VOIP Application = 2048
	// Optimize encoding for non-voice signals like music
	APPLICATION_AUDIO Application = 2049
	// Optimize encoding for low latency applications
	APPLICATION_RESTRICTED_LOWDELAY Application = 2051
)

const (
	xMAX_BITRATE       = 48000
	xMAX_FRAME_SIZE_MS = 60
	xMAX_FRAME_SIZE    = xMAX_BITRATE * xMAX_FRAME_SIZE_MS / 1000
)

func Version() string {
	return C.GoString(C.opus_get_version_string())
}

type Encoder struct {
	p *C.struct_OpusEncoder
}

func opuserr(code int) error {
	return fmt.Errorf("opus: %s", C.GoString(C.opus_strerror(C.int(code))))
}

func NewEncoder(sample_rate int, channels int, application Application) (*Encoder, error) {
	var errno int
	p := C.opus_encoder_create(C.opus_int32(sample_rate), C.int(channels), C.int(application), (*C.int)(unsafe.Pointer(&errno)))
	if errno != 0 {
		return nil, opuserr(errno)
	}
	return &Encoder{p: p}, nil
}

func (enc *Encoder) EncodeFloat32(pcm []float32) ([]byte, error) {
	if pcm == nil || len(pcm) == 0 {
		return nil, fmt.Errorf("opus: no data supplied")
	}
	// I never know how much to allocate
	data := make([]byte, 10000)
	n := int(C.opus_encode_float(
		enc.p,
		(*C.float)(&pcm[0]),
		C.int(len(pcm)),
		(*C.uchar)(&data[0]),
		C.opus_int32(cap(data))))
	if n < 0 {
		return nil, opuserr(n)
	}
	return data[:n], nil
}

// Returns an error if the encoder was already closed
func (enc *Encoder) Close() error {
	if enc.p == nil {
		return fmt.Errorf("opus: encoder already closed")
	}
	C.opus_encoder_destroy(enc.p)
	enc.p = nil
	return nil
}

type Decoder struct {
	p           *C.struct_OpusDecoder
	sample_rate int
}

func NewDecoder(sample_rate int, channels int) (*Decoder, error) {
	var errno int
	p := C.opus_decoder_create(C.opus_int32(sample_rate), C.int(channels), (*C.int)(unsafe.Pointer(&errno)))
	if errno != 0 {
		return nil, opuserr(errno)
	}
	dec := &Decoder{
		p:           p,
		sample_rate: sample_rate,
	}
	return dec, nil
}

func (dec *Decoder) DecodeFloat32(data []byte) ([]float32, error) {
	if data == nil || len(data) == 0 {
		return nil, fmt.Errorf("opus: no data supplied")
	}
	// I don't know how big this frame will be, but this is the limit
	pcm := make([]float32, xMAX_FRAME_SIZE_MS*dec.sample_rate/1000)
	n := int(C.opus_decode_float(
		dec.p,
		(*C.uchar)(&data[0]),
		C.opus_int32(len(data)),
		(*C.float)(&pcm[0]),
		C.int(cap(pcm)),
		0))
	if n < 0 {
		return nil, opuserr(n)
	}
	return pcm[:n], nil
}

// Returns an error if the encoder was already closed
func (dec *Decoder) Close() error {
	if dec.p == nil {
		return fmt.Errorf("opus: decoder already closed")
	}
	C.opus_decoder_destroy(dec.p)
	dec.p = nil
	return nil
}
<|endoftext|>


<commit_before>package lily

import (
	"fmt"
	"net/url"
	"strconv"
)

func ExtractPaginationPars(pars *url.Values) (offset uint64, limit uint64, page uint64) {
	var err error
	qPar := pars.Get("page_size")
	if qPar != "" {
		limit, err = strconv.ParseUint(qPar, 10, 64)
		if err != nil {
			limit = 0
		}
	}
	if limit == 0 {
		limit = 30
	}
	qPar = pars.Get("page")
	if qPar != "" {
		page, err = strconv.ParseUint(qPar, 10, 64)
		if err != nil {
			page = 0
		}
	}
	if page == 0 {
		page = 1
	}
	offset = (page - 1) * limit
	return
}

func ExtractSortPars(pars *url.Values) (sortColumn string, sortDesc bool) {
	// TODO change this fun
	sortColumn = pars.Get("sort_columns")
	qPar := pars.Get("sort_order")
	sortDesc = qPar == "desc"
	return
}

func PaginatedResponse(data string, page_size, page, total uint64) string {
	return fmt.Sprintf(`{"page_size":%d,"page":%d,"total_count":%d`, page_size, page, total) +
		`,"results":` + data + `}`
}
<commit_msg>add json funs<commit_after>package lily

import (
	"fmt"
	"net/url"
	"strconv"
)

func ApiExtractPaginationPars(pars *url.Values) (offset uint64, limit uint64, page uint64) {
	var err error
	qPar := pars.Get("page_size")
	if qPar != "" {
		limit, err = strconv.ParseUint(qPar, 10, 64)
		if err != nil {
			limit = 0
		}
	}
	if limit == 0 {
		limit = 30
	}
	qPar = pars.Get("page")
	if qPar != "" {
		page, err = strconv.ParseUint(qPar, 10, 64)
		if err != nil {
			page = 0
		}
	}
	if page == 0 {
		page = 1
	}
	offset = (page - 1) * limit
	return
}

func ApiExtractSortPars(pars *url.Values) (sortColumn string, sortDesc bool) {
	// TODO change this fun
	sortColumn = pars.Get("sort_columns")
	qPar := pars.Get("sort_order")
	sortDesc = qPar == "desc"
	return
}

func ApiPaginatedResponse(data string, page_size, page, total uint64) string {
	return fmt.Sprintf(`{"page_size":%d,"page":%d,"total_count":%d`, page_size, page, total) +
		`,"results":` + data + `}`
}

func ApiJsonListQuery(q string) string {
	return `(select coalesce(array_to_json(array_agg(row_to_json(sq.*))), '[]')
		from (` + q + `) sq)`
}

func ApiJsonListStrQuery(q string) string {
	return `select coalesce(array_to_json(array_agg(row_to_json(sq.*)))::text, '[]')
		from (` + q + `) sq`
}

func ApiJsonRowQuery(q string) string {
	return `(select row_to_json(sq.*) from (` + q + `) sq)`
}

func ApiJsonRowStrQuery(q string) string {
	return `select row_to_json(sq.*)::text from (` + q + `) sq`
}
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// 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
//
//     https://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 v3 contains samples for Google Cloud Translation API v3.
package v3

// [START translate_v3_create_glossary]
import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// createGlossary creates a glossary to use for other operations.
func createGlossary(w io.Writer, projectID string, location string, glossaryID string, glossaryInputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "glossary-id"
	// glossaryInputURI := "gs://cloud-samples-data/translation/glossary.csv"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.CreateGlossaryRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Glossary: &translatepb.Glossary{
			Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
			Languages: &translatepb.Glossary_LanguageCodesSet_{
				LanguageCodesSet: &translatepb.Glossary_LanguageCodesSet{
					LanguageCodes: []string{"en", "ja"},
				},
			},
			InputConfig: &translatepb.GlossaryInputConfig{
				Source: &translatepb.GlossaryInputConfig_GcsSource{
					GcsSource: &translatepb.GcsSource{
						InputUri: glossaryInputURI,
					},
				},
			},
		},
	}

	// The CreateGlossary operation is async.
	op, err := client.CreateGlossary(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateGlossary: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Created: %v\n", resp.GetName())
	fmt.Fprintf(w, "Input URI: %v\n", resp.InputConfig.GetGcsSource().GetInputUri())

	return nil
}

// [END translate_v3_create_glossary]
<commit_msg>translate: update create_glossary.go sample value (#1120)<commit_after>// Copyright 2019 Google LLC
//
// 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
//
//     https://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 v3 contains samples for Google Cloud Translation API v3.
package v3

// [START translate_v3_create_glossary]
import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// createGlossary creates a glossary to use for other operations.
func createGlossary(w io.Writer, projectID string, location string, glossaryID string, glossaryInputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "my-glossary-display-name"
	// glossaryInputURI := "gs://cloud-samples-data/translation/glossary.csv"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.CreateGlossaryRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Glossary: &translatepb.Glossary{
			Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
			Languages: &translatepb.Glossary_LanguageCodesSet_{
				LanguageCodesSet: &translatepb.Glossary_LanguageCodesSet{
					LanguageCodes: []string{"en", "ja"},
				},
			},
			InputConfig: &translatepb.GlossaryInputConfig{
				Source: &translatepb.GlossaryInputConfig_GcsSource{
					GcsSource: &translatepb.GcsSource{
						InputUri: glossaryInputURI,
					},
				},
			},
		},
	}

	// The CreateGlossary operation is async.
	op, err := client.CreateGlossary(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateGlossary: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Created: %v\n", resp.GetName())
	fmt.Fprintf(w, "Input URI: %v\n", resp.InputConfig.GetGcsSource().GetInputUri())

	return nil
}

// [END translate_v3_create_glossary]
<|endoftext|>