<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	path "path/filepath"
	"regexp"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/howeyc/fsnotify"
	"github.com/mitchellh/go-ps"
	"github.com/silenceper/log"
)

var (
	cmd          *exec.Cmd
	state        sync.Mutex
	eventTime    = make(map[string]int64)
	scheduleTime time.Time
)

// NewWatcher new watcher
func NewWatcher(paths []string, files []string) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Errorf(" Fail to create new Watcher[ %s ]\n", err)
		os.Exit(2)
	}

	go func() {
		for {
			select {
			case e := <-watcher.Event:
				isbuild := true

				// Skip ignored files
				if shouldIgnoreFile(e.Name) {
					continue
				}
				if !checkIfWatchExt(e.Name) {
					continue
				}

				mt := getFileModTime(e.Name)
				if t := eventTime[e.Name]; mt == t {
					// log.Infof("[SKIP] # %s #\n", e.String())
					isbuild = false
				}

				eventTime[e.Name] = mt

				if isbuild {
					go func() {
						// Wait 1s before autobuild util there is no file change.
						scheduleTime = time.Now().Add(1 * time.Second)
						for {
							time.Sleep(time.Until(scheduleTime))
							if time.Now().After(scheduleTime) {
								break
							}
						}

						Autobuild(files)
					}()
				}
			case err := <-watcher.Error:
				log.Errorf("%v", err)
				log.Warnf(" %s\n", err.Error()) // No need to exit here
			}
		}
	}()

	log.Infof("Initializing watcher...\n")
	for _, path := range paths {
		log.Infof("Directory( %s )\n", path)
		err = watcher.Watch(path)
		if err != nil {
			log.Errorf("Fail to watch directory[ %s ]\n", err)
			os.Exit(2)
		}
	}
}

// getFileModTime retuens unix timestamp of `os.File.ModTime` by given path.
func getFileModTime(path string) int64 {
	path = strings.ReplaceAll(path, "\\", "/")
	f, err := os.Open(path)
	if err != nil {
		log.Errorf("Fail to open file[ %s ]\n", err)
		return time.Now().Unix()
	}
	defer f.Close()

	fi, err := f.Stat()
	if err != nil {
		log.Errorf("Fail to get file information[ %s ]\n", err)
		return time.Now().Unix()
	}

	return fi.ModTime().Unix()
}

var building bool

// Autobuild auto build
func Autobuild(files []string) {
	if building {
		log.Infof("still in building...\n")
		return
	}
	building = true
	defer func() {
		building = false
	}()
	state.Lock()
	defer state.Unlock()

	log.Infof("Start building...\n")

	if err := os.Chdir(currpath); err != nil {
		log.Errorf("Chdir Error: %+v\n", err)
		return
	}

	for _, prevCmd := range cfg.PrevBuildCmds {
		log.Infof("Run external cmd '%s'", prevCmd)
		cmdArr := strings.Split(prevCmd, " ")
		prevCmdExec := exec.Command(cmdArr[0])
		prevCmdExec.Env = append(os.Environ(), cfg.Envs...)
		prevCmdExec.Args = cmdArr
		prevCmdExec.Stdout = os.Stdout
		prevCmdExec.Stderr = os.Stderr
		err := prevCmdExec.Run()
		if err != nil {
			panic(err)
		}
	}

	cmdName := "go"

	var err error

	args := []string{"build"}
	args = append(args, "-o", cfg.Output)
	args = append(args, cfg.BuildArgs...)
	if cfg.BuildTags != "" {
		args = append(args, "-tags", cfg.BuildTags)
	}
	args = append(args, files...)

	bcmd := exec.Command(cmdName, args...)
	bcmd.Env = append(os.Environ(), "GOGC=off")
	bcmd.Stdout = os.Stdout
	bcmd.Stderr = os.Stderr
	log.Infof("Build Args: %s %s", cmdName, strings.Join(args, " "))
	err = bcmd.Run()

	if err != nil {
		log.Errorf("============== Build failed ===================\n")
		log.Errorf("%+v\n", err)
		return
	}
	log.Infof("Build was successful\n")
	if !cfg.DisableRun {
		if len(cfg.RunCmd) != 0 {
			Restart(cfg.RunCmd, true)
		} else {
			Restart(cfg.Output, false)
		}
	}
}

// Kill kill main process and all its children
func Kill() {
	defer func() {
		if e := recover(); e != nil {
			fmt.Println("Kill.recover -> ", e)
		}
	}()
	if cmd != nil && cmd.Process != nil {
		// err := cmd.Process.Kill()
		err := killAllProcesses(cmd.Process.Pid)
		if err != nil {
			fmt.Println("Kill -> ", err)
		}
	}
}

// kill main process and all its children
func killAllProcesses(pid int) (err error) {
	hasAllKilled := make(chan bool)
	go func() {
		pids, err := psTree(pid)
		if err != nil {
			log.Fatalf("getting all sub processes error: %v\n", err)
			return
		}
		log.Debugf("main pid: %d", pid)
		log.Debugf("pids: %+v", pids)

		for _, subPid := range pids {
			_ = killProcess(subPid)
		}

		waitForProcess(pid, hasAllKilled)
	}()

	// finally kill the main process
	<-hasAllKilled
	log.Debugf("killing MAIN process pid: %d", pid)
	err = cmd.Process.Kill()
	if err != nil {
		return
	}
	log.Debugf("kill MAIN process succeed")

	return
}

func killProcess(pid int) (err error) {
	log.Debugf("killing process pid: %d", pid)
	ps, err := os.FindProcess(pid)
	if err != nil {
		log.Errorf("find process %d error: %v\n", pid, err)
		return
	}
	err = ps.Kill()
	if err != nil {
		log.Errorf("killing process %d error: %v\n", pid, err)
		// retry
		time.AfterFunc(2*time.Second, func() {
			log.Debugf("retry killing process pid: %d", pid)
			_ = killProcess(pid)
		})
		return
	}
	return
}

// implement pstree based on the cross-platform ps utility in go, go-ps
func psTree(rootPid int) (res []int, err error) {
	pidOfInterest := map[int]struct{}{rootPid: {}}
	pss, err := ps.Processes()
	if err != nil {
		fmt.Println("ERROR: ", err)
		return
	}

	// we must sort the ps by ppid && pid first, otherwise we probably will miss some sub-processes
	// of the root process during for-range searching
	sort.Slice(pss, func(i, j int) bool {
		ppidLess := pss[i].PPid() < pss[j].PPid()
		pidLess := pss[i].PPid() == pss[j].PPid() && pss[i].Pid() < pss[j].Pid()

		return ppidLess || pidLess
	})

	for _, ps := range pss {
		ppid := ps.PPid()
		if _, exists := pidOfInterest[ppid]; exists {
			pidOfInterest[ps.Pid()] = struct{}{}
		}
	}

	for pid := range pidOfInterest {
		if pid != rootPid {
			res = append(res, pid)
		}
	}

	return
}

func waitForProcess(pid int, hasAllKilled chan bool) {
	pids, _ := psTree(pid)
	if len(pids) == 0 {
		hasAllKilled <- true
		return
	}

	log.Infof("still waiting for %d processes %+v to exit", len(pids), pids)
	time.AfterFunc(time.Second, func() {
		waitForProcess(pid, hasAllKilled)
	})
}

// Restart restart app
func Restart(appname string, isCmd bool) {
	// log.Debugf("kill running process")
	Kill()
	go Start(appname, isCmd)
}

// Start start app
func Start(appname string, isCmd bool) {
	log.Infof("Restarting %s ...\n", appname)
	if !strings.HasPrefix(appname, "./") && !isCmd {
		appname = "./" + appname
	}

	cmd = exec.Command(appname)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Args = append([]string{appname}, cfg.CmdArgs...)
	cmd.Env = append(os.Environ(), cfg.Envs...)
	log.Infof("Run %s", strings.Join(cmd.Args, " "))
	go func() {
		_ = cmd.Run()
	}()

	log.Infof("%s is running...\n", appname)
	started <- true
}

// Should ignore filenames generated by
// Emacs, Vim or SublimeText
func shouldIgnoreFile(filename string) bool {
	for _, regex := range ignoredFilesRegExps {
		r, err := regexp.Compile(regex)
		if err != nil {
			panic("Could not compile the regex: " + regex)
		}
		if r.MatchString(filename) {
			return true
		}
		continue
	}
	return false
}

// checkIfWatchExt returns true if the name HasSuffix <watch_ext>.
func checkIfWatchExt(name string) bool {
	for _, s := range cfg.WatchExts {
		if strings.HasSuffix(name, s) {
			return true
		}
	}
	return false
}

func readAppDirectories(directory string, paths *[]string) {
	fileInfos, err := ioutil.ReadDir(directory)
	if err != nil {
		return
	}

	useDirectory := false
	for _, fileInfo := range fileInfos {
		if strings.HasSuffix(fileInfo.Name(), "docs") {
			continue
		}
		if strings.HasSuffix(fileInfo.Name(), "swagger") {
			continue
		}

		if !cfg.VendorWatch && strings.HasSuffix(fileInfo.Name(), "vendor") {
			continue
		}

		if isExcluded(path.Join(directory, fileInfo.Name())) {
			continue
		}

		if fileInfo.IsDir() && fileInfo.Name()[0] != '.' {
			readAppDirectories(directory+"/"+fileInfo.Name(), paths)
			continue
		}
		if useDirectory {
			continue
		}
		*paths = append(*paths, directory)
		useDirectory = true
	}
}

// If a file is excluded
func isExcluded(filePath string) bool {
	for _, p := range cfg.ExcludedPaths {
		absP, err := path.Abs(p)
		if err != nil {
			log.Errorf("err =%v", err)
			log.Errorf("Can not get absolute path of [ %s ]\n", p)
			continue
		}
		absFilePath, err := path.Abs(filePath)
		if err != nil {
			log.Errorf("Can not get absolute path of [ %s ]\n", filePath)
			break
		}
		if strings.HasPrefix(absFilePath, absP) {
			log.Infof("Excluding from watching [ %s ]\n", filePath)
			return true
		}
	}
	return false
}
<commit_msg>nolint:funlen<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	path "path/filepath"
	"regexp"
	"sort"
	"strings"
	"time"

	"github.com/howeyc/fsnotify"
	"github.com/mitchellh/go-ps"
	"github.com/silenceper/log"
)

var (
	cmd          *exec.Cmd
	eventTime    = make(map[string]int64)
	scheduleTime time.Time
)

// NewWatcher new watcher
func NewWatcher(paths []string, files []string) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Errorf(" Fail to create new Watcher[ %s ]\n", err)
		os.Exit(2)
	}

	go func() {
		for {
			select {
			case e := <-watcher.Event:
				isbuild := true

				// Skip ignored files
				if shouldIgnoreFile(e.Name) {
					continue
				}
				if !checkIfWatchExt(e.Name) {
					continue
				}

				mt := getFileModTime(e.Name)
				if t := eventTime[e.Name]; mt == t {
					// log.Infof("[SKIP] # %s #\n", e.String())
					isbuild = false
				}

				eventTime[e.Name] = mt

				if isbuild {
					go func() {
						// Wait 1s before autobuild util there is no file change.
						scheduleTime = time.Now().Add(1 * time.Second)
						for {
							time.Sleep(time.Until(scheduleTime))
							if time.Now().After(scheduleTime) {
								break
							}
						}

						Autobuild(files)
					}()
				}
			case err := <-watcher.Error:
				log.Errorf("%v", err)
				log.Warnf(" %s\n", err.Error()) // No need to exit here
			}
		}
	}()

	log.Infof("Initializing watcher...\n")
	for _, path := range paths {
		log.Infof("Directory( %s )\n", path)
		err = watcher.Watch(path)
		if err != nil {
			log.Errorf("Fail to watch directory[ %s ]\n", err)
			os.Exit(2)
		}
	}
}

// getFileModTime retuens unix timestamp of `os.File.ModTime` by given path.
func getFileModTime(path string) int64 {
	path = strings.ReplaceAll(path, "\\", "/")
	f, err := os.Open(path)
	if err != nil {
		log.Errorf("Fail to open file[ %s ]\n", err)
		return time.Now().Unix()
	}
	defer f.Close()

	fi, err := f.Stat()
	if err != nil {
		log.Errorf("Fail to get file information[ %s ]\n", err)
		return time.Now().Unix()
	}

	return fi.ModTime().Unix()
}

var building bool

// Autobuild auto build
// nolint:funlen
func Autobuild(files []string) {
	if building {
		log.Infof("still in building...\n")
		return
	}
	building = true
	defer func() {
		building = false
	}()

	log.Infof("Start building...\n")

	if err := os.Chdir(currpath); err != nil {
		log.Errorf("Chdir Error: %+v\n", err)
		return
	}

	for _, prevCmd := range cfg.PrevBuildCmds {
		log.Infof("Run external cmd '%s'", prevCmd)
		cmdArr := strings.Split(prevCmd, " ")
		prevCmdExec := exec.Command(cmdArr[0])
		prevCmdExec.Env = append(os.Environ(), cfg.Envs...)
		prevCmdExec.Args = cmdArr
		prevCmdExec.Stdout = os.Stdout
		prevCmdExec.Stderr = os.Stderr
		err := prevCmdExec.Run()
		if err != nil {
			panic(err)
		}
	}

	cmdName := "go"

	var err error

	args := []string{"build"}
	args = append(args, "-o", cfg.Output)
	args = append(args, cfg.BuildArgs...)
	if cfg.BuildTags != "" {
		args = append(args, "-tags", cfg.BuildTags)
	}
	args = append(args, files...)

	bcmd := exec.Command(cmdName, args...)
	bcmd.Env = append(os.Environ(), "GOGC=off")
	bcmd.Stdout = os.Stdout
	bcmd.Stderr = os.Stderr
	log.Infof("Build Args: %s %s", cmdName, strings.Join(args, " "))
	err = bcmd.Run()

	if err != nil {
		log.Errorf("============== Build failed ===================\n")
		log.Errorf("%+v\n", err)
		return
	}
	log.Infof("Build was successful\n")
	if !cfg.DisableRun {
		if len(cfg.RunCmd) != 0 {
			Restart(cfg.RunCmd, true)
		} else {
			Restart(cfg.Output, false)
		}
	}
}

// Kill kill main process and all its children
func Kill() {
	defer func() {
		if e := recover(); e != nil {
			fmt.Println("Kill.recover -> ", e)
		}
	}()
	if cmd != nil && cmd.Process != nil {
		// err := cmd.Process.Kill()
		err := killAllProcesses(cmd.Process.Pid)
		if err != nil {
			fmt.Println("Kill -> ", err)
		}
	}
}

// kill main process and all its children
func killAllProcesses(pid int) (err error) {
	hasAllKilled := make(chan bool)
	go func() {
		pids, err := psTree(pid)
		if err != nil {
			log.Fatalf("getting all sub processes error: %v\n", err)
			return
		}
		log.Debugf("main pid: %d", pid)
		log.Debugf("pids: %+v", pids)

		for _, subPid := range pids {
			_ = killProcess(subPid)
		}

		waitForProcess(pid, hasAllKilled)
	}()

	// finally kill the main process
	<-hasAllKilled
	log.Debugf("killing MAIN process pid: %d", pid)
	err = cmd.Process.Kill()
	if err != nil {
		return
	}
	log.Debugf("kill MAIN process succeed")

	return
}

func killProcess(pid int) (err error) {
	log.Debugf("killing process pid: %d", pid)
	ps, err := os.FindProcess(pid)
	if err != nil {
		log.Errorf("find process %d error: %v\n", pid, err)
		return
	}
	err = ps.Kill()
	if err != nil {
		log.Errorf("killing process %d error: %v\n", pid, err)
		// retry
		time.AfterFunc(2*time.Second, func() {
			log.Debugf("retry killing process pid: %d", pid)
			_ = killProcess(pid)
		})
		return
	}
	return
}

// implement pstree based on the cross-platform ps utility in go, go-ps
func psTree(rootPid int) (res []int, err error) {
	pidOfInterest := map[int]struct{}{rootPid: {}}
	pss, err := ps.Processes()
	if err != nil {
		fmt.Println("ERROR: ", err)
		return
	}

	// we must sort the ps by ppid && pid first, otherwise we probably will miss some sub-processes
	// of the root process during for-range searching
	sort.Slice(pss, func(i, j int) bool {
		ppidLess := pss[i].PPid() < pss[j].PPid()
		pidLess := pss[i].PPid() == pss[j].PPid() && pss[i].Pid() < pss[j].Pid()

		return ppidLess || pidLess
	})

	for _, ps := range pss {
		ppid := ps.PPid()
		if _, exists := pidOfInterest[ppid]; exists {
			pidOfInterest[ps.Pid()] = struct{}{}
		}
	}

	for pid := range pidOfInterest {
		if pid != rootPid {
			res = append(res, pid)
		}
	}

	return
}

func waitForProcess(pid int, hasAllKilled chan bool) {
	pids, _ := psTree(pid)
	if len(pids) == 0 {
		hasAllKilled <- true
		return
	}

	log.Infof("still waiting for %d processes %+v to exit", len(pids), pids)
	time.AfterFunc(time.Second, func() {
		waitForProcess(pid, hasAllKilled)
	})
}

// Restart restart app
func Restart(appname string, isCmd bool) {
	// log.Debugf("kill running process")
	Kill()
	go Start(appname, isCmd)
}

// Start start app
func Start(appname string, isCmd bool) {
	log.Infof("Restarting %s ...\n", appname)
	if !strings.HasPrefix(appname, "./") && !isCmd {
		appname = "./" + appname
	}

	cmd = exec.Command(appname)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Args = append([]string{appname}, cfg.CmdArgs...)
	cmd.Env = append(os.Environ(), cfg.Envs...)
	log.Infof("Run %s", strings.Join(cmd.Args, " "))
	go func() {
		_ = cmd.Run()
	}()

	log.Infof("%s is running...\n", appname)
	started <- true
}

// Should ignore filenames generated by
// Emacs, Vim or SublimeText
func shouldIgnoreFile(filename string) bool {
	for _, regex := range ignoredFilesRegExps {
		r, err := regexp.Compile(regex)
		if err != nil {
			panic("Could not compile the regex: " + regex)
		}
		if r.MatchString(filename) {
			return true
		}
		continue
	}
	return false
}

// checkIfWatchExt returns true if the name HasSuffix <watch_ext>.
func checkIfWatchExt(name string) bool {
	for _, s := range cfg.WatchExts {
		if strings.HasSuffix(name, s) {
			return true
		}
	}
	return false
}

func readAppDirectories(directory string, paths *[]string) {
	fileInfos, err := ioutil.ReadDir(directory)
	if err != nil {
		return
	}

	useDirectory := false
	for _, fileInfo := range fileInfos {
		if strings.HasSuffix(fileInfo.Name(), "docs") {
			continue
		}
		if strings.HasSuffix(fileInfo.Name(), "swagger") {
			continue
		}

		if !cfg.VendorWatch && strings.HasSuffix(fileInfo.Name(), "vendor") {
			continue
		}

		if isExcluded(path.Join(directory, fileInfo.Name())) {
			continue
		}

		if fileInfo.IsDir() && fileInfo.Name()[0] != '.' {
			readAppDirectories(directory+"/"+fileInfo.Name(), paths)
			continue
		}
		if useDirectory {
			continue
		}
		*paths = append(*paths, directory)
		useDirectory = true
	}
}

// If a file is excluded
func isExcluded(filePath string) bool {
	for _, p := range cfg.ExcludedPaths {
		absP, err := path.Abs(p)
		if err != nil {
			log.Errorf("err =%v", err)
			log.Errorf("Can not get absolute path of [ %s ]\n", p)
			continue
		}
		absFilePath, err := path.Abs(filePath)
		if err != nil {
			log.Errorf("Can not get absolute path of [ %s ]\n", filePath)
			break
		}
		if strings.HasPrefix(absFilePath, absP) {
			log.Infof("Excluding from watching [ %s ]\n", filePath)
			return true
		}
	}
	return false
}
<|endoftext|>


<commit_before>// Copyright 2015 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package factom

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

func ECBalance(key string) (int64, error) {
	str := fmt.Sprintf("http://%s/v1/entry-credit-balance/%s", serverFct, key)
	resp, err := http.Get(str)
	if err != nil {
		return 0, err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return 0, fmt.Errorf("Error getting the balance of %s", key)
	}

	if !b.Success {
		return 0, fmt.Errorf(b.Response)
	}

	v, err := strconv.ParseInt(b.Response, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("Error getting the balance of %s", key)
	}

	return v, nil
}

func FctBalance(key string) (int64, error) {
	str := fmt.Sprintf("http://%s/v1/factoid-balance/%s", serverFct, key)
	resp, err := http.Get(str)
	if err != nil {
		return 0, err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return 0, fmt.Errorf("Error getting the balance of %s", key)
	}

	if !b.Success {
		return 0, fmt.Errorf(b.Response)
	}

	v, err := strconv.ParseInt(b.Response, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("Error getting the balance of %s", key)
	}

	return v, nil
}

func GenerateFactoidAddress(name string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address/%s", serverFct, name)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s", name)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddress(name string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address/%s", serverFct, name)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s", name)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromPrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s", name)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddressFromPrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address-from-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s", name)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromHumanReadablePrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-human-readable-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s", name)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddressFromHumanReadablePrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address-from-human-readable-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s", name)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromMnemonic(name string, mnemonic string) (string, error) {
	name = strings.TrimSpace(name)

	mnemonic = strings.Replace(mnemonic, " ", "%20", -1)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-token-sale/?name=%s&mnemonic=%s", serverFct, name, mnemonic)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s", name)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

<commit_msg>Added more explicit error messages.<commit_after>// Copyright 2015 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package factom

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

func ECBalance(key string) (int64, error) {
	str := fmt.Sprintf("http://%s/v1/entry-credit-balance/%s", serverFct, key)
	resp, err := http.Get(str)
	if err != nil {
		return 0, err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return 0, fmt.Errorf("Error getting the balance of %s", key)
	}

	if !b.Success {
		return 0, fmt.Errorf(b.Response)
	}

	v, err := strconv.ParseInt(b.Response, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("Error getting the balance of %s", key)
	}

	return v, nil
}

func FctBalance(key string) (int64, error) {
	str := fmt.Sprintf("http://%s/v1/factoid-balance/%s", serverFct, key)
	resp, err := http.Get(str)
	if err != nil {
		return 0, err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return 0, fmt.Errorf("Error getting the balance of %s", key)
	}

	if !b.Success {
		return 0, fmt.Errorf(b.Response)
	}

	v, err := strconv.ParseInt(b.Response, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("Error getting the balance of %s", key)
	}

	return v, nil
}

func GenerateFactoidAddress(name string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address/%s", serverFct, name)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddress(name string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address/%s", serverFct, name)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromPrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddressFromPrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address-from-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromHumanReadablePrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-human-readable-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddressFromHumanReadablePrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address-from-human-readable-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromMnemonic(name string, mnemonic string) (string, error) {
	name = strings.TrimSpace(name)

	mnemonic = strings.Replace(mnemonic, " ", "%20", -1)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-token-sale/?name=%s&mnemonic=%s", serverFct, name, mnemonic)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}
<|endoftext|>


<commit_before>package lfs

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/github/git-lfs/git"
	"github.com/rubyist/tracerx"
)

const Version = "0.5.1"

var (
	LargeSizeThreshold = 5 * 1024 * 1024
	TempDir            = filepath.Join(os.TempDir(), "git-lfs")
	UserAgent          string
	LocalWorkingDir    string
	LocalGitDir        string
	LocalMediaDir      string
	LocalLogDir        string
	checkedTempDir     string
)

func TempFile(prefix string) (*os.File, error) {
	if checkedTempDir != TempDir {
		if err := os.MkdirAll(TempDir, 0774); err != nil {
			return nil, err
		}
		checkedTempDir = TempDir
	}

	return ioutil.TempFile(TempDir, prefix)
}

func ResetTempDir() error {
	checkedTempDir = ""
	return os.RemoveAll(TempDir)
}

func LocalMediaPath(sha string) (string, error) {
	path := filepath.Join(LocalMediaDir, sha[0:2], sha[2:4])
	if err := os.MkdirAll(path, 0744); err != nil {
		return "", fmt.Errorf("Error trying to create local media directory in '%s': %s", path, err)
	}

	return filepath.Join(path, sha), nil
}

func Environ() []string {
	osEnviron := os.Environ()
	env := make([]string, 4, len(osEnviron)+4)
	env[0] = fmt.Sprintf("LocalWorkingDir=%s", LocalWorkingDir)
	env[1] = fmt.Sprintf("LocalGitDir=%s", LocalGitDir)
	env[2] = fmt.Sprintf("LocalMediaDir=%s", LocalMediaDir)
	env[3] = fmt.Sprintf("TempDir=%s", TempDir)

	for _, e := range osEnviron {
		if !strings.Contains(e, "GIT_") {
			continue
		}
		env = append(env, e)
	}

	return env
}

func InRepo() bool {
	return LocalWorkingDir != ""
}

func init() {
	var err error

	tracerx.DefaultKey = "GIT"
	tracerx.Prefix = "trace git-lfs: "

	LocalWorkingDir, LocalGitDir, err = resolveGitDir()
	if err == nil {
		LocalMediaDir = filepath.Join(LocalGitDir, "lfs", "objects")
		LocalLogDir = filepath.Join(LocalMediaDir, "logs")
		TempDir = filepath.Join(LocalGitDir, "lfs", "tmp")

		if err := os.MkdirAll(LocalMediaDir, 0744); err != nil {
			panic(fmt.Errorf("Error trying to create objects directory in '%s': %s", LocalMediaDir, err))
		}

		if err := os.MkdirAll(LocalLogDir, 0744); err != nil {
			panic(fmt.Errorf("Error trying to create log directory in '%s': %s", LocalLogDir, err))
		}

		if err := os.MkdirAll(TempDir, 0744); err != nil {
			panic(fmt.Errorf("Error trying to create temp directory in '%s': %s", TempDir, err))
		}

	}

	gitVersion, err := git.Config.Version()
	if err != nil {
		gitVersion = "unknown"
	}

	UserAgent = fmt.Sprintf("git-lfs/%s (GitHub; %s %s; git %s; go %s)", Version,
		runtime.GOOS,
		runtime.GOARCH,
		strings.Replace(gitVersion, "git version ", "", 1),
		strings.Replace(runtime.Version(), "go", "", 1))
}

func resolveGitDir() (string, string, error) {
	wd, err := os.Getwd()
	if err != nil {
		return "", "", err
	}

	return recursiveResolveGitDir(wd)
}

func recursiveResolveGitDir(dir string) (string, string, error) {
	var cleanDir = filepath.Clean(dir)
	if cleanDir[len(cleanDir)-1] == os.PathSeparator {
		return "", "", fmt.Errorf("Git repository not found")
	}

	if filepath.Base(dir) == gitExt {
		return filepath.Dir(dir), dir, nil
	}

	gitDir := filepath.Join(dir, gitExt)
	info, err := os.Stat(gitDir)
	if err != nil {
		return recursiveResolveGitDir(filepath.Dir(dir))
	}

	if info.IsDir() {
		return dir, gitDir, nil
	}

	return processDotGitFile(gitDir)
}

func processDotGitFile(file string) (string, string, error) {
	f, err := os.Open(file)
	defer f.Close()

	if err != nil {
		return "", "", err
	}

	data := make([]byte, 512)
	n, err := f.Read(data)
	if err != nil {
		return "", "", err
	}

	contents := string(data[0:n])
	wd, _ := os.Getwd()
	if strings.HasPrefix(contents, gitPtrPrefix) {
		dir := strings.TrimSpace(strings.Split(contents, gitPtrPrefix)[1])
		absDir, _ := filepath.Abs(dir)
		return wd, absDir, nil
	}

	return wd, "", nil
}

const (
	gitExt       = ".git"
	gitPtrPrefix = "gitdir: "
)
<commit_msg>ンンン ンンン ンン<commit_after>package lfs

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/github/git-lfs/git"
	"github.com/rubyist/tracerx"
)

const Version = "0.5.1"

var (
	LargeSizeThreshold = 5 * 1024 * 1024
	TempDir            = filepath.Join(os.TempDir(), "git-lfs")
	UserAgent          string
	LocalWorkingDir    string
	LocalGitDir        string
	LocalMediaDir      string
	LocalLogDir        string
	checkedTempDir     string
)

func TempFile(prefix string) (*os.File, error) {
	if checkedTempDir != TempDir {
		if err := os.MkdirAll(TempDir, 0774); err != nil {
			return nil, err
		}
		checkedTempDir = TempDir
	}

	return ioutil.TempFile(TempDir, prefix)
}

func ResetTempDir() error {
	checkedTempDir = ""
	return os.RemoveAll(TempDir)
}

func LocalMediaPath(sha string) (string, error) {
	path := filepath.Join(LocalMediaDir, sha[0:2], sha[2:4])
	if err := os.MkdirAll(path, 0744); err != nil {
		return "", fmt.Errorf("Error trying to create local media directory in '%s': %s", path, err)
	}

	return filepath.Join(path, sha), nil
}

func Environ() []string {
	osEnviron := os.Environ()
	env := make([]string, 4, len(osEnviron)+4)
	env[0] = fmt.Sprintf("LocalWorkingDir=%s", LocalWorkingDir)
	env[1] = fmt.Sprintf("LocalGitDir=%s", LocalGitDir)
	env[2] = fmt.Sprintf("LocalMediaDir=%s", LocalMediaDir)
	env[3] = fmt.Sprintf("TempDir=%s", TempDir)

	for _, e := range osEnviron {
		if !strings.Contains(e, "GIT_") {
			continue
		}
		env = append(env, e)
	}

	return env
}

func InRepo() bool {
	return LocalWorkingDir != ""
}

func init() {
	var err error

	tracerx.DefaultKey = "GIT"
	tracerx.Prefix = "trace git-lfs: "

	LocalWorkingDir, LocalGitDir, err = resolveGitDir()
	if err == nil {
		LocalMediaDir = filepath.Join(LocalGitDir, "lfs", "objects")
		LocalLogDir = filepath.Join(LocalMediaDir, "logs")
		TempDir = filepath.Join(LocalGitDir, "lfs", "tmp")

		if err := os.MkdirAll(LocalMediaDir, 0744); err != nil {
			panic(fmt.Errorf("Error trying to create objects directory in '%s': %s", LocalMediaDir, err))
		}

		if err := os.MkdirAll(LocalLogDir, 0744); err != nil {
			panic(fmt.Errorf("Error trying to create log directory in '%s': %s", LocalLogDir, err))
		}

		if err := os.MkdirAll(TempDir, 0744); err != nil {
			panic(fmt.Errorf("Error trying to create temp directory in '%s': %s", TempDir, err))
		}

	}

	gitVersion, err := git.Config.Version()
	if err != nil {
		gitVersion = "unknown"
	}

	UserAgent = fmt.Sprintf("git-lfs/%s (GitHub; %s %s; git %s; go %s)", Version,
		runtime.GOOS,
		runtime.GOARCH,
		strings.Replace(gitVersion, "git version ", "", 1),
		strings.Replace(runtime.Version(), "go", "", 1))
}

func resolveGitDir() (string, string, error) {
	wd, err := os.Getwd()
	if err != nil {
		return "", "", err
	}

	return recursiveResolveGitDir(wd)
}

func recursiveResolveGitDir(dir string) (string, string, error) {
	var cleanDir = filepath.Clean(dir)
	if cleanDir[len(cleanDir)-1] == os.PathSeparator {
		return "", "", fmt.Errorf("Git repository not found")
	}

	if filepath.Base(dir) == gitExt {
		return filepath.Dir(dir), dir, nil
	}

	gitDir := filepath.Join(dir, gitExt)
	info, err := os.Stat(gitDir)
	if err != nil {
		return recursiveResolveGitDir(filepath.Dir(dir))
	}

	if info.IsDir() {
		return dir, gitDir, nil
	}

	return processDotGitFile(gitDir)
}

func processDotGitFile(file string) (string, string, error) {
	f, err := os.Open(file)
	defer f.Close()

	if err != nil {
		return "", "", err
	}

	data := make([]byte, 512)
	n, err := f.Read(data)
	if err != nil {
		return "", "", err
	}

	contents := string(data[0:n])
	wd, _ := os.Getwd()
	if strings.HasPrefix(contents, gitPtrPrefix) {
		dir := strings.TrimSpace(strings.Split(contents, gitPtrPrefix)[1])

		if filepath.IsAbs(dir) {
			// The .git file contains an absolute path.
			return wd, dir, nil
		}

		// The .git file contains a relative path.
		// Create an absolute path based on the directory the .git file is located in.
		absDir := filepath.Join(filepath.Dir(file), dir)

		return wd, absDir, nil
	}

	return wd, "", nil
}

const (
	gitExt       = ".git"
	gitPtrPrefix = "gitdir: "
)
<|endoftext|>


<commit_before>package azurerm

import (
	"fmt"
	"log"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/jen20/riviera/azure"
	"github.com/jen20/riviera/sql"
)

func resourceArmSqlDatabase() *schema.Resource {
	return &schema.Resource{
		Create: resourceArmSqlDatabaseCreate,
		Read:   resourceArmSqlDatabaseRead,
		Update: resourceArmSqlDatabaseCreate,
		Delete: resourceArmSqlDatabaseDelete,

		Schema: map[string]*schema.Schema{
			"name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"location": {
				Type:      schema.TypeString,
				Required:  true,
				ForceNew:  true,
				StateFunc: azureRMNormalizeLocation,
			},

			"resource_group_name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"server_name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"create_mode": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Default",
			},

			"source_database_id": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"restore_point_in_time": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"edition": {
				Type:         schema.TypeString,
				Optional:     true,
				Computed:     true,
				ValidateFunc: validateArmSqlDatabaseEdition,
			},

			"collation": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"max_size_bytes": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"requested_service_objective_id": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"requested_service_objective_name": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"source_database_deletion_date": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"elastic_pool_name": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"encryption": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"creation_date": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"default_secondary_location": {
				Type:     schema.TypeString,
				Computed: true,
			},

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

func resourceArmSqlDatabaseCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	rivieraClient := client.rivieraClient

	tags := d.Get("tags").(map[string]interface{})
	expandedTags := expandTags(tags)

	command := &sql.CreateOrUpdateDatabase{
		Name:              d.Get("name").(string),
		Location:          d.Get("location").(string),
		ResourceGroupName: d.Get("resource_group_name").(string),
		ServerName:        d.Get("server_name").(string),
		Tags:              *expandedTags,
		CreateMode:        azure.String(d.Get("create_mode").(string)),
	}

	if v, ok := d.GetOk("source_database_id"); ok {
		command.SourceDatabaseID = azure.String(v.(string))
	}

	if v, ok := d.GetOk("edition"); ok {
		command.Edition = azure.String(v.(string))
	}

	if v, ok := d.GetOk("collation"); ok {
		command.Collation = azure.String(v.(string))
	}

	if v, ok := d.GetOk("max_size_bytes"); ok {
		command.MaxSizeBytes = azure.String(v.(string))
	}

	if v, ok := d.GetOk("source_database_deletion_date"); ok {
		command.SourceDatabaseDeletionDate = azure.String(v.(string))
	}

	if v, ok := d.GetOk("requested_service_objective_id"); ok {
		command.RequestedServiceObjectiveID = azure.String(v.(string))
	}

	if v, ok := d.GetOk("requested_service_objective_name"); ok {
		command.RequestedServiceObjectiveName = azure.String(v.(string))
	}

	createRequest := rivieraClient.NewRequest()
	createRequest.Command = command

	createResponse, err := createRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error creating SQL Database: %s", err)
	}
	if !createResponse.IsSuccessful() {
		return fmt.Errorf("Error creating SQL Database: %s", createResponse.Error)
	}

	readRequest := rivieraClient.NewRequest()
	readRequest.Command = &sql.GetDatabase{
		Name:              d.Get("name").(string),
		ResourceGroupName: d.Get("resource_group_name").(string),
		ServerName:        d.Get("server_name").(string),
	}

	readResponse, err := readRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error reading SQL Database: %s", err)
	}
	if !readResponse.IsSuccessful() {
		return fmt.Errorf("Error reading SQL Database: %s", readResponse.Error)
	}

	resp := readResponse.Parsed.(*sql.GetDatabaseResponse)
	d.SetId(*resp.ID)

	return resourceArmSqlDatabaseRead(d, meta)
}

func resourceArmSqlDatabaseRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	rivieraClient := client.rivieraClient

	readRequest := rivieraClient.NewRequestForURI(d.Id())
	readRequest.Command = &sql.GetDatabase{}

	readResponse, err := readRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error reading SQL Database: %s", err)
	}
	if !readResponse.IsSuccessful() {
		log.Printf("[INFO] Error reading SQL Database %q - removing from state", d.Id())
		d.SetId("")
		return fmt.Errorf("Error reading SQL Database: %s", readResponse.Error)
	}

	resp := readResponse.Parsed.(*sql.GetDatabaseResponse)

	d.Set("name", resp.Name)
	d.Set("creation_date", resp.CreationDate)
	d.Set("default_secondary_location", resp.DefaultSecondaryLocation)

	return nil
}

func resourceArmSqlDatabaseDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	rivieraClient := client.rivieraClient

	deleteRequest := rivieraClient.NewRequestForURI(d.Id())
	deleteRequest.Command = &sql.DeleteDatabase{}

	deleteResponse, err := deleteRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error deleting SQL Database: %s", err)
	}
	if !deleteResponse.IsSuccessful() {
		return fmt.Errorf("Error deleting SQL Database: %s", deleteResponse.Error)
	}

	return nil
}

func validateArmSqlDatabaseEdition(v interface{}, k string) (ws []string, errors []error) {
	editions := map[string]bool{
		"Basic":         true,
		"Standard":      true,
		"Premium":       true,
		"DataWarehouse": true,
	}
	if !editions[v.(string)] {
		errors = append(errors, fmt.Errorf("SQL Database Edition can only be Basic, Standard, Premium or DataWarehouse"))
	}
	return
}
<commit_msg>provider/azurerm: fix sql_database resource reading tags (#9767)<commit_after>package azurerm

import (
	"fmt"
	"log"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/jen20/riviera/azure"
	"github.com/jen20/riviera/sql"
)

func resourceArmSqlDatabase() *schema.Resource {
	return &schema.Resource{
		Create: resourceArmSqlDatabaseCreate,
		Read:   resourceArmSqlDatabaseRead,
		Update: resourceArmSqlDatabaseCreate,
		Delete: resourceArmSqlDatabaseDelete,

		Schema: map[string]*schema.Schema{
			"name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"location": {
				Type:      schema.TypeString,
				Required:  true,
				ForceNew:  true,
				StateFunc: azureRMNormalizeLocation,
			},

			"resource_group_name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"server_name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"create_mode": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Default",
			},

			"source_database_id": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"restore_point_in_time": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"edition": {
				Type:         schema.TypeString,
				Optional:     true,
				Computed:     true,
				ValidateFunc: validateArmSqlDatabaseEdition,
			},

			"collation": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"max_size_bytes": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"requested_service_objective_id": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"requested_service_objective_name": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"source_database_deletion_date": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"elastic_pool_name": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"encryption": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"creation_date": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"default_secondary_location": {
				Type:     schema.TypeString,
				Computed: true,
			},

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

func resourceArmSqlDatabaseCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	rivieraClient := client.rivieraClient

	tags := d.Get("tags").(map[string]interface{})
	expandedTags := expandTags(tags)

	command := &sql.CreateOrUpdateDatabase{
		Name:              d.Get("name").(string),
		Location:          d.Get("location").(string),
		ResourceGroupName: d.Get("resource_group_name").(string),
		ServerName:        d.Get("server_name").(string),
		Tags:              *expandedTags,
		CreateMode:        azure.String(d.Get("create_mode").(string)),
	}

	if v, ok := d.GetOk("source_database_id"); ok {
		command.SourceDatabaseID = azure.String(v.(string))
	}

	if v, ok := d.GetOk("edition"); ok {
		command.Edition = azure.String(v.(string))
	}

	if v, ok := d.GetOk("collation"); ok {
		command.Collation = azure.String(v.(string))
	}

	if v, ok := d.GetOk("max_size_bytes"); ok {
		command.MaxSizeBytes = azure.String(v.(string))
	}

	if v, ok := d.GetOk("source_database_deletion_date"); ok {
		command.SourceDatabaseDeletionDate = azure.String(v.(string))
	}

	if v, ok := d.GetOk("requested_service_objective_id"); ok {
		command.RequestedServiceObjectiveID = azure.String(v.(string))
	}

	if v, ok := d.GetOk("requested_service_objective_name"); ok {
		command.RequestedServiceObjectiveName = azure.String(v.(string))
	}

	createRequest := rivieraClient.NewRequest()
	createRequest.Command = command

	createResponse, err := createRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error creating SQL Database: %s", err)
	}
	if !createResponse.IsSuccessful() {
		return fmt.Errorf("Error creating SQL Database: %s", createResponse.Error)
	}

	readRequest := rivieraClient.NewRequest()
	readRequest.Command = &sql.GetDatabase{
		Name:              d.Get("name").(string),
		ResourceGroupName: d.Get("resource_group_name").(string),
		ServerName:        d.Get("server_name").(string),
	}

	readResponse, err := readRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error reading SQL Database: %s", err)
	}
	if !readResponse.IsSuccessful() {
		return fmt.Errorf("Error reading SQL Database: %s", readResponse.Error)
	}

	resp := readResponse.Parsed.(*sql.GetDatabaseResponse)
	d.SetId(*resp.ID)

	return resourceArmSqlDatabaseRead(d, meta)
}

func resourceArmSqlDatabaseRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	rivieraClient := client.rivieraClient

	readRequest := rivieraClient.NewRequestForURI(d.Id())
	readRequest.Command = &sql.GetDatabase{}

	readResponse, err := readRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error reading SQL Database: %s", err)
	}
	if !readResponse.IsSuccessful() {
		log.Printf("[INFO] Error reading SQL Database %q - removing from state", d.Id())
		d.SetId("")
		return fmt.Errorf("Error reading SQL Database: %s", readResponse.Error)
	}

	resp := readResponse.Parsed.(*sql.GetDatabaseResponse)

	d.Set("name", resp.Name)
	d.Set("creation_date", resp.CreationDate)
	d.Set("default_secondary_location", resp.DefaultSecondaryLocation)

	flattenAndSetTags(d, resp.Tags)

	return nil
}

func resourceArmSqlDatabaseDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	rivieraClient := client.rivieraClient

	deleteRequest := rivieraClient.NewRequestForURI(d.Id())
	deleteRequest.Command = &sql.DeleteDatabase{}

	deleteResponse, err := deleteRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error deleting SQL Database: %s", err)
	}
	if !deleteResponse.IsSuccessful() {
		return fmt.Errorf("Error deleting SQL Database: %s", deleteResponse.Error)
	}

	return nil
}

func validateArmSqlDatabaseEdition(v interface{}, k string) (ws []string, errors []error) {
	editions := map[string]bool{
		"Basic":         true,
		"Standard":      true,
		"Premium":       true,
		"DataWarehouse": true,
	}
	if !editions[v.(string)] {
		errors = append(errors, fmt.Errorf("SQL Database Edition can only be Basic, Standard, Premium or DataWarehouse"))
	}
	return
}
<|endoftext|>


<commit_before>// Package webserver is the newest webserver.
package webserver

// Copyright (c) 2020, Mitchell Cooper
// quiki - a standalone web server for wikifier

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

	"github.com/cooper/quiki/wikifier"
	"github.com/pkg/errors"
)

var conf *wikifier.Page
var mux *http.ServeMux

// Server represents a quiki webserver.
type Server struct {
	Server *http.Server
	Mux    *http.ServeMux
	Conf   *wikifier.Page
	bind   string
	port   string
}

// New initializes the webserver and returns it.
func New(confFile string) *Server {
	mux = http.NewServeMux()

	// parse configuration
	conf = wikifier.NewPage(confFile)
	conf.VarsOnly = true
	if err := conf.Parse(); err != nil {
		log.Fatal(errors.Wrap(err, "parse config"))
	}

	var port, bind, dirStatic string
	for key, ptr := range map[string]*string{
		"server.http.port":    &port,
		"server.http.bind":    &bind,
		"server.dir.template": &templateDirs,
		"server.dir.static":   &dirStatic,
	} {
		str, err := conf.GetStr(key)
		if err != nil {
			log.Fatal(err)
		}
		*ptr = str
	}

	// set up wikis
	if err := initWikis(); err != nil {
		log.Fatal(errors.Wrap(err, "init wikis"))
	}

	// setup static files from wikifier
	if err := setupStatic(dirStatic); err != nil {
		log.Fatal(errors.Wrap(err, "setup static"))
	}

	log.Println("quiki ready")

	// create server with main handler
	mux.HandleFunc("/", handleRoot)
	server := &http.Server{Handler: mux}

	// create webserver
	return &Server{
		Server: server,
		Mux:    mux,
		Conf:   conf,
		port:   port,
		bind:   bind,
	}
}

// Listen runs the webserver indefinitely.
//
// If any errors occur, the program is terminated.
func (s *Server) Listen() {
	if s.port == "unix" {
		listener, err := net.Listen("unix", s.bind)
		if err != nil {
			log.Fatal(errors.Wrap(err, "listen"))
		}
		s.Server.Serve(listener)
	} else {
		s.Server.Addr = s.bind + ":" + s.port
		log.Fatal(errors.Wrap(s.Server.ListenAndServe(), "listen"))
	}
}

func setupStatic(staticPath string) error {
	if stat, err := os.Stat(staticPath); err != nil || !stat.IsDir() {
		if err == nil {
			err = errors.New("not a directory")
		}
		return err
	}
	fileServer := http.FileServer(http.Dir(staticPath))
	mux.Handle("/static/", http.StripPrefix("/static/", fileServer))
	return nil
}
<commit_msg>normalize paths from server configuration<commit_after>// Package webserver is the newest webserver.
package webserver

// Copyright (c) 2020, Mitchell Cooper
// quiki - a standalone web server for wikifier

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

	"github.com/cooper/quiki/wikifier"
	"github.com/pkg/errors"
)

var conf *wikifier.Page
var mux *http.ServeMux

// Server represents a quiki webserver.
type Server struct {
	Server *http.Server
	Mux    *http.ServeMux
	Conf   *wikifier.Page
	bind   string
	port   string
}

// New initializes the webserver and returns it.
func New(confFile string) *Server {
	mux = http.NewServeMux()

	// parse configuration
	conf = wikifier.NewPage(confFile)
	conf.VarsOnly = true
	if err := conf.Parse(); err != nil {
		log.Fatal(errors.Wrap(err, "parse config"))
	}

	// extract strings
	var port, bind, dirStatic string
	for key, ptr := range map[string]*string{
		"server.http.port":    &port,
		"server.http.bind":    &bind,
		"server.dir.template": &templateDirs,
		"server.dir.static":   &dirStatic,
	} {
		str, err := conf.GetStr(key)
		if err != nil {
			log.Fatal(err)
		}
		*ptr = str
	}

	// normalize paths
	templateDirs = filepath.FromSlash(templateDirs)
	dirStatic = filepath.FromSlash(dirStatic)

	// set up wikis
	if err := initWikis(); err != nil {
		log.Fatal(errors.Wrap(err, "init wikis"))
	}

	// setup static files from wikifier
	if err := setupStatic(dirStatic); err != nil {
		log.Fatal(errors.Wrap(err, "setup static"))
	}

	log.Println("quiki ready")

	// create server with main handler
	mux.HandleFunc("/", handleRoot)
	server := &http.Server{Handler: mux}

	// create webserver
	return &Server{
		Server: server,
		Mux:    mux,
		Conf:   conf,
		port:   port,
		bind:   bind,
	}
}

// Listen runs the webserver indefinitely.
//
// If any errors occur, the program is terminated.
func (s *Server) Listen() {
	if s.port == "unix" {
		listener, err := net.Listen("unix", s.bind)
		if err != nil {
			log.Fatal(errors.Wrap(err, "listen"))
		}
		s.Server.Serve(listener)
	} else {
		s.Server.Addr = s.bind + ":" + s.port
		log.Fatal(errors.Wrap(s.Server.ListenAndServe(), "listen"))
	}
}

func setupStatic(staticPath string) error {
	if stat, err := os.Stat(staticPath); err != nil || !stat.IsDir() {
		if err == nil {
			err = errors.New("not a directory")
		}
		return err
	}
	fileServer := http.FileServer(http.Dir(staticPath))
	mux.Handle("/static/", http.StripPrefix("/static/", fileServer))
	return nil
}
<|endoftext|>


<commit_before>package resources

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/dynamodb"
)

type DynamoDBTable struct {
	svc *dynamodb.DynamoDB
	id  string
}

func init() {
	register("DynamoDBTable", ListDynamoDBTables)
}

func ListDynamoDBTables(sess *session.Session) ([]Resource, error) {
	svc := dynamodb.New(sess)

	resp, err := svc.ListTables(&dynamodb.ListTablesInput{})
	if err != nil {
		return nil, err
	}

	resources := make([]Resource, 0)
	for _, tableName := range resp.TableNames {
		resources = append(resources, &DynamoDBTable{
			svc: svc,
			id:  *tableName,
		})
	}

	return resources, nil
}

func (i *DynamoDBTable) Remove() error {
	params := &dynamodb.DeleteTableInput{
		TableName: aws.String(i.id),
	}

	_, err := i.svc.DeleteTable(params)
	if err != nil {
		return err
	}

	return nil
}

func (i *DynamoDBTable) String() string {
	return i.id
}
<commit_msg>Add tag filter for dynamodb tables<commit_after>package resources

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/rebuy-de/aws-nuke/pkg/types"
)

type DynamoDBTable struct {
	svc  *dynamodb.DynamoDB
	id   string
	tags []*dynamodb.Tag
}

func init() {
	register("DynamoDBTable", ListDynamoDBTables)
}

func ListDynamoDBTables(sess *session.Session) ([]Resource, error) {
	svc := dynamodb.New(sess)

	resp, err := svc.ListTables(&dynamodb.ListTablesInput{})
	if err != nil {
		return nil, err
	}

	resources := make([]Resource, 0)
	for _, tableName := range resp.TableNames {
		tags, err := GetTableTags(svc, tableName)

		if err != nil {
			continue
		}

		resources = append(resources, &DynamoDBTable{
			svc: svc,
			id:  *tableName,
			tags: tags,
		})
	}

	return resources, nil
}

func (i *DynamoDBTable) Remove() error {
	params := &dynamodb.DeleteTableInput{
		TableName: aws.String(i.id),
	}

	_, err := i.svc.DeleteTable(params)
	if err != nil {
		return err
	}

	return nil
}

func GetTableTags(svc *dynamodb.DynamoDB, tableName *string) ([]*dynamodb.Tag, error) {
	result, err := svc.DescribeTable(&dynamodb.DescribeTableInput{
		TableName: aws.String(*tableName),
	})

	if err != nil {
		return make([]*dynamodb.Tag, 0), err
	}

	tags, err :=  svc.ListTagsOfResource(&dynamodb.ListTagsOfResourceInput{
		ResourceArn: result.Table.TableArn,
	})

	if err != nil {
		return make([]*dynamodb.Tag, 0), err
	}

	return tags.Tags, nil
}

func (i *DynamoDBTable) Properties() types.Properties {
        properties := types.NewProperties()
        properties.Set("Identifier", i.id)

        for _, tag := range i.tags {
                properties.SetTag(tag.Key, tag.Value)
        }

        return properties
}

func (i *DynamoDBTable) String() string {
	return i.id
}
<|endoftext|>


<commit_before>package rpcquery

import (
	"context"
	"fmt"

	"github.com/hyperledger/burrow/txs/payload"

	"github.com/hyperledger/burrow/execution/proposal"

	"github.com/hyperledger/burrow/acm"
	"github.com/hyperledger/burrow/acm/state"
	"github.com/hyperledger/burrow/bcm"
	"github.com/hyperledger/burrow/consensus/tendermint"
	"github.com/hyperledger/burrow/event/query"
	"github.com/hyperledger/burrow/execution/names"
	"github.com/hyperledger/burrow/logging"
	"github.com/hyperledger/burrow/rpc"
)

type queryServer struct {
	accounts    state.IterableStatsReader
	nameReg     names.IterableReader
	proposalReg proposal.IterableReader
	blockchain  bcm.BlockchainInfo
	nodeView    *tendermint.NodeView
	logger      *logging.Logger
}

var _ QueryServer = &queryServer{}

func NewQueryServer(state state.IterableStatsReader, nameReg names.IterableReader, proposalReg proposal.IterableReader,
	blockchain bcm.BlockchainInfo, nodeView *tendermint.NodeView, logger *logging.Logger) *queryServer {
	return &queryServer{
		accounts:    state,
		nameReg:     nameReg,
		proposalReg: proposalReg,
		blockchain:  blockchain,
		nodeView:    nodeView,
		logger:      logger,
	}
}

func (qs *queryServer) Status(ctx context.Context, param *StatusParam) (*rpc.ResultStatus, error) {
	return rpc.Status(qs.blockchain, qs.nodeView, param.BlockTimeWithin, param.BlockSeenTimeWithin)
}

// Account state

func (qs *queryServer) GetAccount(ctx context.Context, param *GetAccountParam) (*acm.Account, error) {
	acc, err := qs.accounts.GetAccount(param.Address)
	if acc == nil {
		acc = &acm.Account{}
	}
	return acc, err
}

func (qs *queryServer) ListAccounts(param *ListAccountsParam, stream Query_ListAccountsServer) error {
	qry, err := query.NewBuilder(param.Query).Query()
	var streamErr error
	_, err = qs.accounts.IterateAccounts(func(acc *acm.Account) (stop bool) {
		if qry.Matches(acc.Tagged()) {
			streamErr = stream.Send(acc)
			if streamErr != nil {
				return true
			}
		}
		return
	})
	if err != nil {
		return err
	}
	return streamErr
}

// Name registry
func (qs *queryServer) GetName(ctx context.Context, param *GetNameParam) (entry *names.Entry, err error) {
	entry, err = qs.nameReg.GetName(param.Name)
	if entry == nil && err == nil {
		err = fmt.Errorf("name %s not found", param.Name)
	}
	return
}

func (qs *queryServer) ListNames(param *ListNamesParam, stream Query_ListNamesServer) error {
	qry, err := query.NewBuilder(param.Query).Query()
	if err != nil {
		return err
	}
	var streamErr error
	_, err = qs.nameReg.IterateNames(func(entry *names.Entry) (stop bool) {
		if qry.Matches(entry.Tagged()) {
			streamErr = stream.Send(entry)
			if streamErr != nil {
				return true
			}
		}
		return
	})
	if err != nil {
		return err
	}
	return streamErr
}

func (qs *queryServer) GetValidatorSet(ctx context.Context, param *GetValidatorSetParam) (*ValidatorSet, error) {
	set, deltas, height := qs.blockchain.ValidatorsHistory()
	vs := &ValidatorSet{
		Height: height,
		Set:    set.Validators(),
	}
	if param.IncludeHistory {
		vs.History = make([]*ValidatorSetDeltas, len(deltas))
		for i, d := range deltas {
			vs.History[i] = &ValidatorSetDeltas{
				Validators: d.Validators(),
			}
		}
	}
	return vs, nil
}

func (qs *queryServer) GetProposal(ctx context.Context, param *GetProposalParam) (proposal *payload.Ballot, err error) {
	proposal, err = qs.proposalReg.GetProposal(param.Hash)
	if proposal == nil && err == nil {
		err = fmt.Errorf("proposal %x not found", param.Hash)
	}
	return
}

func (qs *queryServer) ListProposals(param *ListProposalsParam, stream Query_ListProposalsServer) error {
	var streamErr error
	_, err := qs.proposalReg.IterateProposals(func(hash []byte, ballot *payload.Ballot) (stop bool) {
		if param.GetProposed() == true || ballot.ProposalState == payload.Ballot_PROPOSED {
			streamErr = stream.Send(&ProposalResult{Hash: hash, Ballot: ballot})
			if streamErr != nil {
				return true
			}
		}
		return
	})
	if err != nil {
		return err
	}
	return streamErr
}

func (qs *queryServer) GetStats(ctx context.Context, param *GetStatsParam) (*Stats, error) {
	stats := qs.accounts.GetAccountStats()

	return &Stats{
		AccountsWithCode:    stats.AccountsWithCode,
		AccountsWithoutCode: stats.AccountsWithoutCode,
	}, nil
}
<commit_msg>Make --list-proposed=all etc work<commit_after>package rpcquery

import (
	"context"
	"fmt"

	"github.com/hyperledger/burrow/txs/payload"

	"github.com/hyperledger/burrow/execution/proposal"

	"github.com/hyperledger/burrow/acm"
	"github.com/hyperledger/burrow/acm/state"
	"github.com/hyperledger/burrow/bcm"
	"github.com/hyperledger/burrow/consensus/tendermint"
	"github.com/hyperledger/burrow/event/query"
	"github.com/hyperledger/burrow/execution/names"
	"github.com/hyperledger/burrow/logging"
	"github.com/hyperledger/burrow/rpc"
)

type queryServer struct {
	accounts    state.IterableStatsReader
	nameReg     names.IterableReader
	proposalReg proposal.IterableReader
	blockchain  bcm.BlockchainInfo
	nodeView    *tendermint.NodeView
	logger      *logging.Logger
}

var _ QueryServer = &queryServer{}

func NewQueryServer(state state.IterableStatsReader, nameReg names.IterableReader, proposalReg proposal.IterableReader,
	blockchain bcm.BlockchainInfo, nodeView *tendermint.NodeView, logger *logging.Logger) *queryServer {
	return &queryServer{
		accounts:    state,
		nameReg:     nameReg,
		proposalReg: proposalReg,
		blockchain:  blockchain,
		nodeView:    nodeView,
		logger:      logger,
	}
}

func (qs *queryServer) Status(ctx context.Context, param *StatusParam) (*rpc.ResultStatus, error) {
	return rpc.Status(qs.blockchain, qs.nodeView, param.BlockTimeWithin, param.BlockSeenTimeWithin)
}

// Account state

func (qs *queryServer) GetAccount(ctx context.Context, param *GetAccountParam) (*acm.Account, error) {
	acc, err := qs.accounts.GetAccount(param.Address)
	if acc == nil {
		acc = &acm.Account{}
	}
	return acc, err
}

func (qs *queryServer) ListAccounts(param *ListAccountsParam, stream Query_ListAccountsServer) error {
	qry, err := query.NewBuilder(param.Query).Query()
	var streamErr error
	_, err = qs.accounts.IterateAccounts(func(acc *acm.Account) (stop bool) {
		if qry.Matches(acc.Tagged()) {
			streamErr = stream.Send(acc)
			if streamErr != nil {
				return true
			}
		}
		return
	})
	if err != nil {
		return err
	}
	return streamErr
}

// Name registry
func (qs *queryServer) GetName(ctx context.Context, param *GetNameParam) (entry *names.Entry, err error) {
	entry, err = qs.nameReg.GetName(param.Name)
	if entry == nil && err == nil {
		err = fmt.Errorf("name %s not found", param.Name)
	}
	return
}

func (qs *queryServer) ListNames(param *ListNamesParam, stream Query_ListNamesServer) error {
	qry, err := query.NewBuilder(param.Query).Query()
	if err != nil {
		return err
	}
	var streamErr error
	_, err = qs.nameReg.IterateNames(func(entry *names.Entry) (stop bool) {
		if qry.Matches(entry.Tagged()) {
			streamErr = stream.Send(entry)
			if streamErr != nil {
				return true
			}
		}
		return
	})
	if err != nil {
		return err
	}
	return streamErr
}

func (qs *queryServer) GetValidatorSet(ctx context.Context, param *GetValidatorSetParam) (*ValidatorSet, error) {
	set, deltas, height := qs.blockchain.ValidatorsHistory()
	vs := &ValidatorSet{
		Height: height,
		Set:    set.Validators(),
	}
	if param.IncludeHistory {
		vs.History = make([]*ValidatorSetDeltas, len(deltas))
		for i, d := range deltas {
			vs.History[i] = &ValidatorSetDeltas{
				Validators: d.Validators(),
			}
		}
	}
	return vs, nil
}

func (qs *queryServer) GetProposal(ctx context.Context, param *GetProposalParam) (proposal *payload.Ballot, err error) {
	proposal, err = qs.proposalReg.GetProposal(param.Hash)
	if proposal == nil && err == nil {
		err = fmt.Errorf("proposal %x not found", param.Hash)
	}
	return
}

func (qs *queryServer) ListProposals(param *ListProposalsParam, stream Query_ListProposalsServer) error {
	var streamErr error
	_, err := qs.proposalReg.IterateProposals(func(hash []byte, ballot *payload.Ballot) (stop bool) {
		if param.GetProposed() == false || ballot.ProposalState == payload.Ballot_PROPOSED {
			streamErr = stream.Send(&ProposalResult{Hash: hash, Ballot: ballot})
			if streamErr != nil {
				return true
			}
		}
		return
	})
	if err != nil {
		return err
	}
	return streamErr
}

func (qs *queryServer) GetStats(ctx context.Context, param *GetStatsParam) (*Stats, error) {
	stats := qs.accounts.GetAccountStats()

	return &Stats{
		AccountsWithCode:    stats.AccountsWithCode,
		AccountsWithoutCode: stats.AccountsWithoutCode,
	}, nil
}
<|endoftext|>


<commit_before>package h5

var (
	// Scopes
	allScope = map[string]bool{}
	baseScope = map[string]bool{
		"applet":true,
		"caption":true,
		"html":true,
		"table":true,
		"td":true,
		"th":true,
		"marquee":true,
		"object":true,
		"mi":true,
		"mo":true,
		"mn":true,
		"ms":true,
		"mtext":true,
		"annotation-xml":true,
		"foreignObject":true,
		"desc":true,
		"title":true,
	}
	buttonScope = map[string]bool{
		"applet":true,
		"caption":true,
		"html":true,
		"table":true,
		"td":true,
		"th":true,
		"marquee":true,
		"object":true,
		"mi":true,
		"mo":true,
		"mn":true,
		"ms":true,
		"mtext":true,
		"annotation-xml":true,
		"foreignObject":true,
		"desc":true,
		"title":true,
		"button":true,
	}
	listScope = map[string]bool{
		"applet":true,
		"caption":true,
		"html":true,
		"table":true,
		"td":true,
		"th":true,
		"marquee":true,
		"object":true,
		"mi":true,
		"mo":true,
		"mn":true,
		"ms":true,
		"mtext":true,
		"annotation-xml":true,
		"foreignObject":true,
		"desc":true,
		"title":true,
		"ol":true,
		"ul":true,
	}
)<commit_msg>go fmt.<commit_after>package h5

var (
	// Scopes
	allScope  = map[string]bool{}
	baseScope = map[string]bool{
		"applet":         true,
		"caption":        true,
		"html":           true,
		"table":          true,
		"td":             true,
		"th":             true,
		"marquee":        true,
		"object":         true,
		"mi":             true,
		"mo":             true,
		"mn":             true,
		"ms":             true,
		"mtext":          true,
		"annotation-xml": true,
		"foreignObject":  true,
		"desc":           true,
		"title":          true,
	}
	buttonScope = map[string]bool{
		"applet":         true,
		"caption":        true,
		"html":           true,
		"table":          true,
		"td":             true,
		"th":             true,
		"marquee":        true,
		"object":         true,
		"mi":             true,
		"mo":             true,
		"mn":             true,
		"ms":             true,
		"mtext":          true,
		"annotation-xml": true,
		"foreignObject":  true,
		"desc":           true,
		"title":          true,
		"button":         true,
	}
	listScope = map[string]bool{
		"applet":         true,
		"caption":        true,
		"html":           true,
		"table":          true,
		"td":             true,
		"th":             true,
		"marquee":        true,
		"object":         true,
		"mi":             true,
		"mo":             true,
		"mn":             true,
		"ms":             true,
		"mtext":          true,
		"annotation-xml": true,
		"foreignObject":  true,
		"desc":           true,
		"title":          true,
		"ol":             true,
		"ul":             true,
	}
)
<|endoftext|>


<commit_before>package rest

import (
	"reflect"
)

func NewHandler() *Handler {
	handler := new(Handler)
	handler.apis = apis{}
	return handler
}

type apis map[string]IApiWrapper

type Handler struct {
	apis apis
}

func (self *Handler) Api(val interface{}) IApiWrapper {
	typ := reflect.TypeOf(val)
	for _, apiw := range self.apis {
		if reflect.TypeOf(apiw.Api()) == typ {
			return apiw
		}
	}

	return nil
}

func (self *Handler) Add(name string, api *ApiWrapper) {
	if self.Has(name) {
		panic("Api " + name + " already exists")
	}

	api.Init()
	self.apis[name] = api
}

func (self *Handler) Has(apiName string) bool {
	for name, _ := range self.apis {
		if name == apiName {
			return true
		}
	}

	return false
}

func (self *Handler) Get(apiName string) IApiWrapper {
	for name, ApiWrapper := range self.apis {
		if name == apiName {
			return ApiWrapper
		}
	}

	return nil
}
<commit_msg>cache the api reflect.Type<commit_after>package rest

import "reflect"

func NewHandler() *Handler {
	handler := new(Handler)
	handler.apis = apis{}
	return handler
}

type apis map[string]*apiItem

type apiItem struct {
	apiType reflect.Type
	api     IApiWrapper
}

func (self *apiItem) Type() reflect.Type {
	if self.apiType == nil {
		self.apiType = reflect.TypeOf(self.api.Api())
	}

	return self.apiType
}

type Handler struct {
	apis apis
}

func (self *Handler) Api(val interface{}) IApiWrapper {
	typ := reflect.TypeOf(val)
	for _, a := range self.apis {
		if a.Type() == typ {
			return a.api
		}
	}

	return nil
}

func (self *Handler) Add(name string, api *ApiWrapper) {
	if self.Has(name) {
		panic("Api " + name + " already exists")
	}

	api.Init()
	self.apis[name] = &apiItem{
		api: api,
	}
}

func (self *Handler) Has(apiName string) bool {
	for name, _ := range self.apis {
		if name == apiName {
			return true
		}
	}

	return false
}

func (self *Handler) Get(apiName string) IApiWrapper {
	for name, a := range self.apis {
		if name == apiName {
			return a.api
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"fmt"
	"os"

	"github.com/joatmon08/docker-consul-handler/lib"
	"github.com/joatmon08/docker-consul-handler/runner"
)

func main() {
	ansible_runner, ok := os.LookupEnv("CONSUL_HANDLER_RUNNER")
	if !ok {
		panic("Environment variable CONSUL_HANDER_RUNNER is not set!")
	}

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	runner_client := runner.Client{URL: ansible_runner}

	for scanner.Scan() {
		input := scanner.Bytes()
		network, err := lib.GetNewestNetwork(input)
		if len(network) > 0 {
			if err != nil {
				panic(err)
			}
			play_body := []byte(fmt.Sprintf("{\"container_network\": \"%s\"}", network))
			if _, err = runner_client.Play(play_body); err != nil {
				fmt.Printf("Network %s not created", network)
			}
		}
	}

	if err := scanner.Err(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
<commit_msg>Updated handler.<commit_after>package main

import (
	"bufio"
	"fmt"
	"os"

	"github.com/joatmon08/docker-consul-handler/lib"
	"github.com/joatmon08/docker-consul-handler/runner"
)

func main() {
	ansible_runner, ok := os.LookupEnv("CONSUL_HANDLER_RUNNER")
	if !ok {
		panic("Environment variable CONSUL_HANDER_RUNNER is not set!")
	}

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	runner_client := runner.Client{URL: ansible_runner}

	for scanner.Scan() {
		input := scanner.Bytes()
		network, err := lib.GetNewestNetwork(input)
		if len(network) > 0 {
			if err != nil {
				panic(err)
			}
			play_body := []byte(fmt.Sprintf("{\"container_network\": \"%s\"}", network))
			fmt.Printf("Body %s", play_body)
			if _, err = runner_client.Play(play_body); err != nil {
				fmt.Printf("Network %s not created", network)
			}
		}
	}

	if err := scanner.Err(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/golang/groupcache"
	"github.com/gorilla/mux"
	"io"
	"math/rand"
	"net/http"
	"time"
	"vip/fetch"
)

type UploadResponse struct {
	Url string `json:"url"`
}

type verifyAuth func(http.ResponseWriter, *http.Request)

func (h verifyAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	auth := r.Header.Get("X-Vip-Token")
	if auth != authToken {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	h(w, r)
}

func fileKey(bucket string) string {
	seed := rand.New(rand.NewSource(time.Now().UnixNano()))
	key := fmt.Sprintf("%d-%s-%d", seed.Int63(), bucket, time.Now().UnixNano())

	hash := md5.New()
	io.WriteString(hash, key)
	return fmt.Sprintf("%x", hash.Sum(nil))
}

func handleImageRequest(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		w.WriteHeader(http.StatusMethodNotAllowed)
	}

	w.Header().Set("Cache-Control", "public, max-age=31536000")

	// Client is checking for a cached URI, assume it is valid
	// and return a 304
	if r.Header.Get("If-Modified-Since") != "" {
		w.WriteHeader(http.StatusNotModified)
		return
	}

	gc := fetch.RequestContext(r)

	var data []byte
	err := cache.Get(gc, gc.CacheKey(), groupcache.AllocatingByteSliceSink(&data))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	w.Header().Set("Content-Type", http.DetectContentType(data))
	http.ServeContent(w, r, gc.ImageId, time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), bytes.NewReader(data))
}

func handleUpload(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.WriteHeader(http.StatusMethodNotAllowed)
	}

	vars := mux.Vars(r)
	bucket := vars["bucket_id"]

	// Set a hard 5mb limit on files
	if r.ContentLength > 6<<20 {
		w.WriteHeader(http.StatusRequestEntityTooLarge)
		return
	}

	key := fileKey(bucket)
	err := storage.PutReader(bucket, key, r.Body,
		r.ContentLength, r.Header.Get("Content-Type"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer r.Body.Close()

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	uri := r.URL
	uri.Path = fmt.Sprintf("%s/%s", bucket, key)

	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(UploadResponse{
		Url: uri.String(),
	})
}

func handlePing(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "pong")
}
<commit_msg>Enable environment config for hostname<commit_after>package main

import (
	"bytes"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/golang/groupcache"
	"github.com/gorilla/mux"
	"io"
	"math/rand"
	"net/http"
	"os"
	"time"
	"vip/fetch"
)

type UploadResponse struct {
	Url string `json:"url"`
}

type verifyAuth func(http.ResponseWriter, *http.Request)

func (h verifyAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	auth := r.Header.Get("X-Vip-Token")
	if auth != authToken {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	h(w, r)
}

func fileKey(bucket string) string {
	seed := rand.New(rand.NewSource(time.Now().UnixNano()))
	key := fmt.Sprintf("%d-%s-%d", seed.Int63(), bucket, time.Now().UnixNano())

	hash := md5.New()
	io.WriteString(hash, key)
	return fmt.Sprintf("%x", hash.Sum(nil))
}

func handleImageRequest(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		w.WriteHeader(http.StatusMethodNotAllowed)
	}

	w.Header().Set("Cache-Control", "public, max-age=31536000")

	// Client is checking for a cached URI, assume it is valid
	// and return a 304
	if r.Header.Get("If-Modified-Since") != "" {
		w.WriteHeader(http.StatusNotModified)
		return
	}

	gc := fetch.RequestContext(r)

	var data []byte
	err := cache.Get(gc, gc.CacheKey(), groupcache.AllocatingByteSliceSink(&data))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	w.Header().Set("Content-Type", http.DetectContentType(data))
	http.ServeContent(w, r, gc.ImageId, time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), bytes.NewReader(data))
}

func handleUpload(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.WriteHeader(http.StatusMethodNotAllowed)
	}

	vars := mux.Vars(r)
	bucket := vars["bucket_id"]

	// Set a hard 5mb limit on files
	if r.ContentLength > 6<<20 {
		w.WriteHeader(http.StatusRequestEntityTooLarge)
		return
	}

	key := fileKey(bucket)
	err := storage.PutReader(bucket, key, r.Body,
		r.ContentLength, r.Header.Get("Content-Type"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer r.Body.Close()

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	uri := r.URL

	if r.URL.Host == "" {
		uri.Host = os.Getenv("URI_HOSTNAME")
		uri.Scheme = "http"
	}

	uri.Path = fmt.Sprintf("%s/%s", bucket, key)

	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(UploadResponse{
		Url: uri.String(),
	})
}

func handlePing(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "pong")
}
<|endoftext|>