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

// author       sigu-399
// author-github  https://github.com/sigu-399
// author-mail    sigu.399@gmail.com
//
// repository-name  jsonreference
// repository-desc  An implementation of JSON Reference - Go language
//
// description    Main and unique file.
//
// created        26-02-2013

package jsonreference

import (
	"errors"
	"net/url"
	"strings"

	"github.com/PuerkitoBio/purell"
	"github.com/go-swagger/go-swagger/jsonpointer"
)

const (
	fragmentRune = `#`
)

// New creates a new reference for the given string
func New(jsonReferenceString string) (Ref, error) {

	var r Ref
	err := r.parse(jsonReferenceString)
	return r, err

}

// MustCreateRef parses the ref string and panics when it's invalid.
// Use the New method for a version that returns an error
func MustCreateRef(ref string) Ref {
	r, err := New(ref)
	if err != nil {
		panic(err)
	}
	return r
}

// Ref represents a json reference object
type Ref struct {
	referenceURL     *url.URL
	referencePointer jsonpointer.Pointer

	HasFullURL      bool
	HasURLPathOnly  bool
	HasFragmentOnly bool
	HasFileScheme   bool
	HasFullFilePath bool
}

// GetURL gets the URL for this reference
func (r *Ref) GetURL() *url.URL {
	return r.referenceURL
}

// GetPointer gets the json pointer for this reference
func (r *Ref) GetPointer() *jsonpointer.Pointer {
	return &r.referencePointer
}

// String returns the best version of the url for this reference
func (r *Ref) String() string {

	if r.referenceURL != nil {
		return r.referenceURL.String()
	}

	if r.HasFragmentOnly {
		return fragmentRune + r.referencePointer.String()
	}

	return r.referencePointer.String()
}

// IsRoot returns true if this reference is a root document
func (r *Ref) IsRoot() bool {
	return r.referenceURL != nil &&
		!r.IsCanonical() &&
		!r.HasURLPathOnly &&
		r.referenceURL.Fragment == ""
}

// IsCanonical returns true when this pointer starts with http(s):// or file://
func (r *Ref) IsCanonical() bool {
	return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL)
}

// "Constructor", parses the given string JSON reference
func (r *Ref) parse(jsonReferenceString string) error {

	parsed, err := url.Parse(jsonReferenceString)
	if err != nil {
		return err
	}

	r.referenceURL, _ = url.Parse(purell.NormalizeURL(parsed, purell.FlagsSafe|purell.FlagRemoveDuplicateSlashes))
	refURL := r.referenceURL

	if refURL.Scheme != "" && refURL.Host != "" {
		r.HasFullURL = true
	} else {
		if refURL.Path != "" {
			r.HasURLPathOnly = true
		} else if refURL.RawQuery == "" && refURL.Fragment != "" {
			r.HasFragmentOnly = true
		}
	}

	r.HasFileScheme = refURL.Scheme == "file"
	r.HasFullFilePath = strings.HasPrefix(refURL.Path, "/")

	// invalid json-pointer error means url has no json-pointer fragment. simply ignore error
	r.referencePointer, _ = jsonpointer.New(refURL.Fragment)

	return nil
}

// Inherits creates a new reference from a parent and a child
// If the child cannot inherit from the parent, an error is returned
func (r *Ref) Inherits(child Ref) (*Ref, error) {
	childURL := child.GetURL()
	parentURL := r.GetURL()
	if childURL == nil {
		return nil, errors.New("child url is nil")
	}
	if parentURL == nil {
		return &child, nil
	}

	ref, _ := New(parentURL.ResolveReference(childURL).String())
	return &ref, nil
}
<commit_msg>fixes #123 fixes wrong name detection for circular ancestry<commit_after>// Copyright 2013 sigu-399 ( https://github.com/sigu-399 )
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// author       sigu-399
// author-github  https://github.com/sigu-399
// author-mail    sigu.399@gmail.com
//
// repository-name  jsonreference
// repository-desc  An implementation of JSON Reference - Go language
//
// description    Main and unique file.
//
// created        26-02-2013

package jsonreference

import (
	"errors"
	"net/url"
	"strings"

	"github.com/PuerkitoBio/purell"
	"github.com/go-swagger/go-swagger/jsonpointer"
)

const (
	fragmentRune = `#`
)

// New creates a new reference for the given string
func New(jsonReferenceString string) (Ref, error) {

	var r Ref
	err := r.parse(jsonReferenceString)
	return r, err

}

// MustCreateRef parses the ref string and panics when it's invalid.
// Use the New method for a version that returns an error
func MustCreateRef(ref string) Ref {
	r, err := New(ref)
	if err != nil {
		panic(err)
	}
	return r
}

// Ref represents a json reference object
type Ref struct {
	referenceURL     *url.URL
	referencePointer jsonpointer.Pointer

	HasFullURL      bool
	HasURLPathOnly  bool
	HasFragmentOnly bool
	HasFileScheme   bool
	HasFullFilePath bool
}

// GetURL gets the URL for this reference
func (r *Ref) GetURL() *url.URL {
	return r.referenceURL
}

// GetPointer gets the json pointer for this reference
func (r *Ref) GetPointer() *jsonpointer.Pointer {
	return &r.referencePointer
}

// String returns the best version of the url for this reference
func (r *Ref) String() string {

	if r.referenceURL != nil {
		return r.referenceURL.String()
	}

	if r.HasFragmentOnly {
		return fragmentRune + r.referencePointer.String()
	}

	return r.referencePointer.String()
}

// IsRoot returns true if this reference is a root document
func (r *Ref) IsRoot() bool {
	return r.referenceURL != nil &&
		!r.IsCanonical() &&
		!r.HasURLPathOnly &&
		r.referenceURL.Fragment == ""
}

// IsCanonical returns true when this pointer starts with http(s):// or file://
func (r *Ref) IsCanonical() bool {
	return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL)
}

// "Constructor", parses the given string JSON reference
func (r *Ref) parse(jsonReferenceString string) error {

	parsed, err := url.Parse(jsonReferenceString)
	if err != nil {
		return err
	}

	r.referenceURL, _ = url.Parse(purell.NormalizeURL(parsed, purell.FlagsSafe|purell.FlagRemoveDuplicateSlashes))
	refURL := r.referenceURL

	if refURL.Scheme != "" && refURL.Host != "" {
		r.HasFullURL = true
	} else {
		if refURL.Path != "" {
			r.HasURLPathOnly = true
		} else if refURL.RawQuery == "" && refURL.Fragment != "" {
			r.HasFragmentOnly = true
		}
	}

	r.HasFileScheme = refURL.Scheme == "file"
	r.HasFullFilePath = strings.HasPrefix(refURL.Path, "/")

	// invalid json-pointer error means url has no json-pointer fragment. simply ignore error
	r.referencePointer, _ = jsonpointer.New(refURL.Fragment)

	return nil
}

// Inherits creates a new reference from a parent and a child
// If the child cannot inherit from the parent, an error is returned
func (r *Ref) Inherits(child Ref) (*Ref, error) {
	childURL := child.GetURL()
	parentURL := r.GetURL()
	if childURL == nil {
		return nil, errors.New("child url is nil")
	}
	if parentURL == nil {
		return &child, nil
	}

	ref, err := New(parentURL.ResolveReference(childURL).String())
	if err != nil {
		return nil, err
	}
	return &ref, nil
}
<|endoftext|>


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

// Package integration provides test-only code for performing integrated
// tests of Trillian functionality.
package integration

import (
	"context"
	"crypto"
	"database/sql"
	"net"
	"sync"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes"
	"github.com/google/trillian"
	"github.com/google/trillian/crypto/keys/der"
	"github.com/google/trillian/crypto/keys/pem"
	"github.com/google/trillian/crypto/keyspb"
	"github.com/google/trillian/extension"
	"github.com/google/trillian/quota"
	"github.com/google/trillian/server"
	"github.com/google/trillian/server/interceptor"
	"github.com/google/trillian/storage/mysql"
	"github.com/google/trillian/storage/testdb"
	"github.com/google/trillian/testonly"
	"github.com/google/trillian/util"
	"google.golang.org/grpc"

	ktestonly "github.com/google/trillian/crypto/keys/testonly"
	stestonly "github.com/google/trillian/storage/testonly"

	_ "github.com/go-sql-driver/mysql"                   // Load MySQL driver
	_ "github.com/google/trillian/crypto/keys/der/proto" // Register PrivateKey ProtoHandler
)

var (
	sequencerWindow = time.Duration(0)
	batchSize       = 50
	// SequencerInterval is the time between runs of the sequencer.
	SequencerInterval = 100 * time.Millisecond
	timeSource        = util.SystemTimeSource{}
	publicKey         = testonly.DemoPublicKey
	privateKeyInfo    = &keyspb.PrivateKey{
		Der: ktestonly.MustMarshalPrivatePEMToDER(testonly.DemoPrivateKey, testonly.DemoPrivateKeyPass),
	}
)

// LogEnv is a test environment that contains both a log server and a connection to it.
type LogEnv struct {
	registry        extension.Registry
	pendingTasks    *sync.WaitGroup
	grpcServer      *grpc.Server
	logServer       *server.TrillianLogRPCServer
	LogOperation    server.LogOperation
	Sequencer       *server.LogOperationManager
	sequencerCancel context.CancelFunc
	Address         string
	ClientConn      *grpc.ClientConn
	DB              *sql.DB
	// PublicKey is the public key that verifies responses from this server.
	PublicKey crypto.PublicKey
}

// NewLogEnv creates a fresh DB, log server, and client. The numSequencers parameter
// indicates how many sequencers to run in parallel; if numSequencers is zero a
// manually-controlled test sequencer is used.
// TODO(codingllama): Remove 3rd parameter (need to coordinate with
// github.com/google/certificate-transparency-go)
func NewLogEnv(ctx context.Context, numSequencers int, _ string) (*LogEnv, error) {
	db, err := testdb.NewTrillianDB(ctx)
	if err != nil {
		return nil, err
	}

	registry := extension.Registry{
		AdminStorage: mysql.NewAdminStorage(db),
		LogStorage:   mysql.NewLogStorage(db, nil),
		QuotaManager: quota.Noop(),
		NewKeyProto: func(ctx context.Context, spec *keyspb.Specification) (proto.Message, error) {
			return der.NewProtoFromSpec(spec)
		},
	}

	ret, err := NewLogEnvWithRegistry(ctx, numSequencers, registry)
	if err != nil {
		db.Close()
		return nil, err
	}
	ret.DB = db
	return ret, nil
}

// NewLogEnvWithRegistry uses the passed in Registry to create a log server,
// and client. The numSequencers parameter indicates how many sequencers to
// run in parallel; if numSequencers is zero a manually-controlled test
// sequencer is used.
func NewLogEnvWithRegistry(ctx context.Context, numSequencers int, registry extension.Registry) (*LogEnv, error) {
	// Create Log Server.
	grpcServer := grpc.NewServer(grpc.UnaryInterceptor(interceptor.ErrorWrapper))
	logServer := server.NewTrillianLogRPCServer(registry, timeSource)
	trillian.RegisterTrillianLogServer(grpcServer, logServer)

	// Create Sequencer.
	sequencerManager := server.NewSequencerManager(registry, sequencerWindow)
	var wg sync.WaitGroup
	var sequencerTask *server.LogOperationManager
	ctx, cancel := context.WithCancel(ctx)
	info := server.LogOperationInfo{
		Registry:    registry,
		BatchSize:   batchSize,
		NumWorkers:  numSequencers,
		RunInterval: SequencerInterval,
		TimeSource:  timeSource,
	}
	// Start a live sequencer in a goroutine.
	sequencerTask = server.NewLogOperationManager(info, sequencerManager)
	wg.Add(1)
	go func(wg *sync.WaitGroup, om *server.LogOperationManager) {
		defer wg.Done()
		om.OperationLoop(ctx)
	}(&wg, sequencerTask)

	// Listen and start server.
	addr, lis, err := listen()
	if err != nil {
		cancel()
		return nil, err
	}
	wg.Add(1)
	go func(wg *sync.WaitGroup, grpcServer *grpc.Server, lis net.Listener) {
		defer wg.Done()
		grpcServer.Serve(lis)
	}(&wg, grpcServer, lis)

	// Connect to the server.
	cc, err := grpc.Dial(addr, grpc.WithInsecure())
	if err != nil {
		cancel()
		return nil, err
	}

	publicKey, err := pem.UnmarshalPublicKey(publicKey)
	if err != nil {
		cancel()
		return nil, err
	}

	return &LogEnv{
		registry:        registry,
		pendingTasks:    &wg,
		grpcServer:      grpcServer,
		logServer:       logServer,
		Address:         addr,
		ClientConn:      cc,
		PublicKey:       publicKey,
		LogOperation:    sequencerManager,
		Sequencer:       sequencerTask,
		sequencerCancel: cancel,
	}, nil
}

// Close shuts down the server.
func (env *LogEnv) Close() {
	if env.sequencerCancel != nil {
		env.sequencerCancel()
	}
	env.ClientConn.Close()
	env.grpcServer.GracefulStop()
	env.pendingTasks.Wait()
	if env.DB != nil {
		env.DB.Close()
	}
}

// CreateLog creates a log and signs the first empty tree head.
func (env *LogEnv) CreateLog() (int64, error) {
	ctx := context.Background()
	tx, err := env.registry.AdminStorage.Begin(ctx)
	if err != nil {
		return 0, err
	}

	tree := stestonly.LogTree
	tree.PrivateKey, err = ptypes.MarshalAny(privateKeyInfo)
	if err != nil {
		return 0, err
	}
	tree.PublicKey = &keyspb.PublicKey{
		Der: ktestonly.MustMarshalPublicPEMToDER(publicKey),
	}

	tree, err = tx.CreateTree(ctx, tree)
	if err != nil {
		return 0, err
	}
	if err := tx.Commit(); err != nil {
		return 0, err
	}
	// Sign the first empty tree head.
	env.Sequencer.OperationSingle(ctx)
	return tree.TreeId, nil
}
<commit_msg>Add an Admin Server to `LogEnv` integration test environments. (#926)<commit_after>// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package integration provides test-only code for performing integrated
// tests of Trillian functionality.
package integration

import (
	"context"
	"crypto"
	"database/sql"
	"net"
	"sync"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes"
	"github.com/google/trillian"
	"github.com/google/trillian/crypto/keys/der"
	"github.com/google/trillian/crypto/keys/pem"
	"github.com/google/trillian/crypto/keyspb"
	"github.com/google/trillian/extension"
	"github.com/google/trillian/quota"
	"github.com/google/trillian/server"
	"github.com/google/trillian/server/admin"
	"github.com/google/trillian/server/interceptor"
	"github.com/google/trillian/storage/mysql"
	"github.com/google/trillian/storage/testdb"
	"github.com/google/trillian/testonly"
	"github.com/google/trillian/util"
	"google.golang.org/grpc"

	ktestonly "github.com/google/trillian/crypto/keys/testonly"
	stestonly "github.com/google/trillian/storage/testonly"

	_ "github.com/go-sql-driver/mysql"                   // Load MySQL driver
	_ "github.com/google/trillian/crypto/keys/der/proto" // Register PrivateKey ProtoHandler
)

var (
	sequencerWindow = time.Duration(0)
	batchSize       = 50
	// SequencerInterval is the time between runs of the sequencer.
	SequencerInterval = 100 * time.Millisecond
	timeSource        = util.SystemTimeSource{}
	publicKey         = testonly.DemoPublicKey
	privateKeyInfo    = &keyspb.PrivateKey{
		Der: ktestonly.MustMarshalPrivatePEMToDER(testonly.DemoPrivateKey, testonly.DemoPrivateKeyPass),
	}
)

// LogEnv is a test environment that contains both a log server and a connection to it.
type LogEnv struct {
	registry        extension.Registry
	pendingTasks    *sync.WaitGroup
	grpcServer      *grpc.Server
	adminServer     *admin.Server
	logServer       *server.TrillianLogRPCServer
	LogOperation    server.LogOperation
	Sequencer       *server.LogOperationManager
	sequencerCancel context.CancelFunc
	Address         string
	ClientConn      *grpc.ClientConn
	DB              *sql.DB
	// PublicKey is the public key that verifies responses from this server.
	PublicKey crypto.PublicKey
}

// NewLogEnv creates a fresh DB, log server, and client. The numSequencers parameter
// indicates how many sequencers to run in parallel; if numSequencers is zero a
// manually-controlled test sequencer is used.
// TODO(codingllama): Remove 3rd parameter (need to coordinate with
// github.com/google/certificate-transparency-go)
func NewLogEnv(ctx context.Context, numSequencers int, _ string) (*LogEnv, error) {
	db, err := testdb.NewTrillianDB(ctx)
	if err != nil {
		return nil, err
	}

	registry := extension.Registry{
		AdminStorage: mysql.NewAdminStorage(db),
		LogStorage:   mysql.NewLogStorage(db, nil),
		QuotaManager: quota.Noop(),
		NewKeyProto: func(ctx context.Context, spec *keyspb.Specification) (proto.Message, error) {
			return der.NewProtoFromSpec(spec)
		},
	}

	ret, err := NewLogEnvWithRegistry(ctx, numSequencers, registry)
	if err != nil {
		db.Close()
		return nil, err
	}
	ret.DB = db
	return ret, nil
}

// NewLogEnvWithRegistry uses the passed in Registry to create a log server,
// and client. The numSequencers parameter indicates how many sequencers to
// run in parallel; if numSequencers is zero a manually-controlled test
// sequencer is used.
func NewLogEnvWithRegistry(ctx context.Context, numSequencers int, registry extension.Registry) (*LogEnv, error) {
	// Create the GRPC Server.
	grpcServer := grpc.NewServer(grpc.UnaryInterceptor(interceptor.ErrorWrapper))

	// Setup the Admin Server.
	adminServer := admin.New(registry, nil)
	trillian.RegisterTrillianAdminServer(grpcServer, adminServer)

	// Setup the Log Server.
	logServer := server.NewTrillianLogRPCServer(registry, timeSource)
	trillian.RegisterTrillianLogServer(grpcServer, logServer)

	// Create Sequencer.
	sequencerManager := server.NewSequencerManager(registry, sequencerWindow)
	var wg sync.WaitGroup
	var sequencerTask *server.LogOperationManager
	ctx, cancel := context.WithCancel(ctx)
	info := server.LogOperationInfo{
		Registry:    registry,
		BatchSize:   batchSize,
		NumWorkers:  numSequencers,
		RunInterval: SequencerInterval,
		TimeSource:  timeSource,
	}
	// Start a live sequencer in a goroutine.
	sequencerTask = server.NewLogOperationManager(info, sequencerManager)
	wg.Add(1)
	go func(wg *sync.WaitGroup, om *server.LogOperationManager) {
		defer wg.Done()
		om.OperationLoop(ctx)
	}(&wg, sequencerTask)

	// Listen and start server.
	addr, lis, err := listen()
	if err != nil {
		cancel()
		return nil, err
	}
	wg.Add(1)
	go func(wg *sync.WaitGroup, grpcServer *grpc.Server, lis net.Listener) {
		defer wg.Done()
		grpcServer.Serve(lis)
	}(&wg, grpcServer, lis)

	// Connect to the server.
	cc, err := grpc.Dial(addr, grpc.WithInsecure())
	if err != nil {
		cancel()
		return nil, err
	}

	publicKey, err := pem.UnmarshalPublicKey(publicKey)
	if err != nil {
		cancel()
		return nil, err
	}

	return &LogEnv{
		registry:        registry,
		pendingTasks:    &wg,
		grpcServer:      grpcServer,
		adminServer:     adminServer,
		logServer:       logServer,
		Address:         addr,
		ClientConn:      cc,
		PublicKey:       publicKey,
		LogOperation:    sequencerManager,
		Sequencer:       sequencerTask,
		sequencerCancel: cancel,
	}, nil
}

// Close shuts down the server.
func (env *LogEnv) Close() {
	if env.sequencerCancel != nil {
		env.sequencerCancel()
	}
	env.ClientConn.Close()
	env.grpcServer.GracefulStop()
	env.pendingTasks.Wait()
	if env.DB != nil {
		env.DB.Close()
	}
}

// CreateLog creates a log and signs the first empty tree head.
func (env *LogEnv) CreateLog() (int64, error) {
	ctx := context.Background()
	tx, err := env.registry.AdminStorage.Begin(ctx)
	if err != nil {
		return 0, err
	}

	tree := stestonly.LogTree
	tree.PrivateKey, err = ptypes.MarshalAny(privateKeyInfo)
	if err != nil {
		return 0, err
	}
	tree.PublicKey = &keyspb.PublicKey{
		Der: ktestonly.MustMarshalPublicPEMToDER(publicKey),
	}

	tree, err = tx.CreateTree(ctx, tree)
	if err != nil {
		return 0, err
	}
	if err := tx.Commit(); err != nil {
		return 0, err
	}
	// Sign the first empty tree head.
	env.Sequencer.OperationSingle(ctx)
	return tree.TreeId, nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"

	net_http "net/http"

	"github.com/ninech/reception/common"
	"github.com/ninech/reception/docker"
	"github.com/ninech/reception/http"
)

func main() {
	fmt.Println("(c) 2017 Nine Internet Solutions AG")

	hostMap := &common.HostToHostMap{
		M: make(map[string]string),
	}

	hostMap.Lock()
	hostMap.M["localhost"] = "google.com:80"
	hostMap.Unlock()

	go runHttpFrontend(hostMap)

	runDockerClient(hostMap)
}
func runDockerClient(hostMap *common.HostToHostMap) {
	err := docker.Client{
		HostMap: hostMap,
	}.Launch()
	if err != nil {
		panic(err)
	}
}

func runHttpFrontend(hostMap *common.HostToHostMap) {
	frontend := &net_http.Server{
		Addr: "localhost:8888",
		Handler: http.BackendHandler{
			HostMapping: hostMap,
		},
	}

	fmt.Println("Starting to listen on ", frontend.Addr)

	err := frontend.ListenAndServe()
	if err != nil {
		panic(err)
	} else {
		defer frontend.Close()
	}
}
<commit_msg>🐛 Fix initialization<commit_after>package main

import (
	"fmt"

	net_http "net/http"

	"github.com/ninech/reception/common"
	"github.com/ninech/reception/docker"
	"github.com/ninech/reception/http"
)

func main() {
	fmt.Println("(c) 2017 Nine Internet Solutions AG")

	hostMap := &common.HostToHostMap{
		M: make(map[string]string),
	}

	hostMap.Lock()
	hostMap.M["localhost"] = "google.com:80"
	hostMap.Unlock()

	go runHttpFrontend(hostMap)

	runDockerClient(hostMap)
}
func runDockerClient(hostMap *common.HostToHostMap) {
	client := docker.Client{
		HostMap: hostMap,
	}
	err := client.Launch()
	if err != nil {
		panic(err)
	}
}

func runHttpFrontend(hostMap *common.HostToHostMap) {
	frontend := &net_http.Server{
		Addr: "localhost:8888",
		Handler: http.BackendHandler{
			HostMapping: hostMap,
		},
	}

	fmt.Println("Starting to listen on ", frontend.Addr)

	err := frontend.ListenAndServe()
	if err != nil {
		panic(err)
	} else {
		defer frontend.Close()
	}
}
<|endoftext|>


<commit_before>package redisence

import (
	"fmt"
	"strconv"
	"sync"
	"time"

	gredis "github.com/garyburd/redigo/redis"
	"github.com/koding/redis"
)

type Status int

const (
	Offline Status = iota
	Online
	Closed
)

// Event is the data type for
// occuring events in the system
type Event struct {
	// Id is the given key by the application
	Id string

	// Status holds the changing type of event
	Status Status
}

// Prefix for redisence package
const RedisencePrefix = "redisence"

// Session holds the required connection data for redis
type Session struct {
	// main redis connection
	redis *redis.RedisSession

	// inactiveDuration specifies no-probe allowance time
	inactiveDuration time.Duration

	// receiving offline events pattern
	becameOfflinePattern string

	// receiving online events pattern
	becameOnlinePattern string
}

func New(server string, db int, inactiveDuration time.Duration) (*Session, error) {
	redis, err := redis.NewRedisSession(&redis.RedisConf{Server: server, DB: db})
	if err != nil {
		return nil, err
	}
	redis.SetPrefix(RedisencePrefix)

	return &Session{
		redis:                redis,
		becameOfflinePattern: fmt.Sprintf("__keyevent@%d__:expired", db),
		becameOnlinePattern:  fmt.Sprintf("__keyevent@%d__:set", db),
		inactiveDuration:     inactiveDuration,
	}, nil
}

// Ping resets the expiration time for any given key
// if key doesnt exists, it means user is now online
// Whenever application gets any prob from a client
// should call this function
func (s *Session) Ping(ids ...string) error {
	if len(ids) == 1 {
		// if member exits increase ttl
		if s.redis.Expire(ids[0], s.inactiveDuration) == nil {
			return nil
		}

		// if member doesnt exist set it
		return s.redis.Setex(ids[0], s.inactiveDuration, ids[0])
	}

	existance, err := s.sendMultiExpire(ids)
	if err != nil {
		return err
	}

	return s.sendMultiSetIfRequired(ids, existance)
}

func (s *Session) sendMultiSetIfRequired(ids []string, existance []int) error {
	if len(ids) != len(existance) {
		return fmt.Errorf("Length is not same Ids: %d Existance: %d", len(ids), len(existance))
	}

	// cache inactive duration as string
	seconds := strconv.Itoa(int(s.inactiveDuration.Seconds()))

	// get one connection from pool
	c := s.redis.Pool().Get()

	// item count for non-existent members
	notExistsCount := 0

	for i, exists := range existance {
		// `0` means, member doesnt exists in presence system
		if exists != 0 {
			continue
		}

		// init multi command lazily
		if notExistsCount == 0 {
			c.Send("MULTI")
		}

		notExistsCount++
		c.Send("SETEX", s.redis.AddPrefix(ids[i]), seconds, ids[i])
	}

	// execute multi command if only we flushed some to connection
	if notExistsCount != 0 {
		// ignore values
		if _, err := c.Do("EXEC"); err != nil {
			return err
		}
	}

	// do not forget to close the connection
	if err := c.Close(); err != nil {
		return err
	}

	return nil
}

func (s *Session) sendMultiExpire(ids []string) ([]int, error) {
	// cache inactive duration as string
	seconds := strconv.Itoa(int(s.inactiveDuration.Seconds()))

	// get one connection from pool
	c := s.redis.Pool().Get()

	// init multi command
	c.Send("MULTI")

	// send expire command for all members
	for _, id := range ids {
		c.Send("EXPIRE", s.redis.AddPrefix(id), seconds)
	}

	// execute command
	r, err := c.Do("EXEC")
	if err != nil {
		return make([]int, 0), err
	}

	// close connection
	if err := c.Close(); err != nil {
		return make([]int, 0), err
	}

	values, err := s.redis.Values(r)
	if err != nil {
		return make([]int, 0), err
	}

	res := make([]int, len(values))
	for i, value := range values {
		res[i], err = s.redis.Int(value)
		if err != nil {
			return make([]int, 0), err
		}

	}

	return res, nil
}

// Status returns the current status a key from system
func (s *Session) Status(ids ...string) ([]Event, error) {
	// get one connection from pool
	c := s.redis.Pool().Get()

	// init multi command
	c.Send("MULTI")

	// send expire command for all members
	for _, id := range ids {
		c.Send("EXISTS", s.redis.AddPrefix(id))
	}

	// execute command
	r, err := c.Do("EXEC")
	if err != nil {
		return make([]Event, 0), err
	}

	// close connection
	if err := c.Close(); err != nil {
		return make([]Event, 0), err
	}

	values, err := s.redis.Values(r)
	if err != nil {
		return make([]Event, 0), err
	}

	res := make([]Event, len(values))
	for i, value := range values {
		status, err := s.redis.Int(value)
		if err != nil {
			return make([]Event, 0), err
		}

		e := Event{
			Id:     ids[i],
			Status: Status(status),
		}

		// if status == 0 {
		// 	e.Status = Offline
		// } else {
		// 	e.Status = Online
		// }
		res[i] = e
	}

	return res, nil
}

// createEvent Creates the event with the required properties
func (s *Session) createEvent(n gredis.PMessage) Event {
	e := Event{}

	switch n.Pattern {
	case s.becameOfflinePattern:
		e.Id = string(n.Data[len(RedisencePrefix)+1:])
		e.Status = Offline
	case s.becameOnlinePattern:
		e.Id = string(n.Data[len(RedisencePrefix)+1:])
		e.Status = Online
	default:
		//ignore other events
	}

	return e
}

// ListenStatusChanges pubscribes to the redis and
// gets online and offline status changes from it
func (s *Session) ListenStatusChanges(events chan Event) {
	psc := s.redis.CreatePubSubConn()

	psc.PSubscribe(s.becameOnlinePattern, s.becameOfflinePattern)

	var wg sync.WaitGroup
	wg.Add(1)

	go func() {
		defer wg.Done()
		for {
			switch n := psc.Receive().(type) {
			case gredis.PMessage:
				events <- s.createEvent(n)
			case error:
				fmt.Printf("error: %v\n", n)
				return
			}
		}
	}()

	// avoid lock
	go func() {
		wg.Wait()
		psc.PUnsubscribe(s.becameOfflinePattern, s.becameOnlinePattern)
		psc.Close()
		events <- Event{Status: Closed}
	}()
}
<commit_msg>Redisence: fix commented line problems<commit_after>package redisence

import (
	"fmt"
	"strconv"
	"sync"
	"time"

	gredis "github.com/garyburd/redigo/redis"
	"github.com/koding/redis"
)

type Status int

const (
	Offline Status = iota
	Online
	Closed
)

// Event is the data type for
// occuring events in the system
type Event struct {
	// Id is the given key by the application
	Id string

	// Status holds the changing type of event
	Status Status
}

// Prefix for redisence package
const RedisencePrefix = "redisence"

// Session holds the required connection data for redis
type Session struct {
	// main redis connection
	redis *redis.RedisSession

	// inactiveDuration specifies no-probe allowance time
	inactiveDuration time.Duration

	// receiving offline events pattern
	becameOfflinePattern string

	// receiving online events pattern
	becameOnlinePattern string
}

func New(server string, db int, inactiveDuration time.Duration) (*Session, error) {
	redis, err := redis.NewRedisSession(&redis.RedisConf{Server: server, DB: db})
	if err != nil {
		return nil, err
	}
	redis.SetPrefix(RedisencePrefix)

	return &Session{
		redis:                redis,
		becameOfflinePattern: fmt.Sprintf("__keyevent@%d__:expired", db),
		becameOnlinePattern:  fmt.Sprintf("__keyevent@%d__:set", db),
		inactiveDuration:     inactiveDuration,
	}, nil
}

// Ping resets the expiration time for any given key
// if key doesnt exists, it means user is now online
// Whenever application gets any prob from a client
// should call this function
func (s *Session) Ping(ids ...string) error {
	if len(ids) == 1 {
		// if member exits increase ttl
		if s.redis.Expire(ids[0], s.inactiveDuration) == nil {
			return nil
		}

		// if member doesnt exist set it
		return s.redis.Setex(ids[0], s.inactiveDuration, ids[0])
	}

	existance, err := s.sendMultiExpire(ids)
	if err != nil {
		return err
	}

	return s.sendMultiSetIfRequired(ids, existance)
}

func (s *Session) sendMultiSetIfRequired(ids []string, existance []int) error {
	if len(ids) != len(existance) {
		return fmt.Errorf("Length is not same Ids: %d Existance: %d", len(ids), len(existance))
	}

	// cache inactive duration as string
	seconds := strconv.Itoa(int(s.inactiveDuration.Seconds()))

	// get one connection from pool
	c := s.redis.Pool().Get()

	// item count for non-existent members
	notExistsCount := 0

	for i, exists := range existance {
		// `0` means, member doesnt exists in presence system
		if exists != 0 {
			continue
		}

		// init multi command lazily
		if notExistsCount == 0 {
			c.Send("MULTI")
		}

		notExistsCount++
		c.Send("SETEX", s.redis.AddPrefix(ids[i]), seconds, ids[i])
	}

	// execute multi command if only we flushed some to connection
	if notExistsCount != 0 {
		// ignore values
		if _, err := c.Do("EXEC"); err != nil {
			return err
		}
	}

	// do not forget to close the connection
	if err := c.Close(); err != nil {
		return err
	}

	return nil
}

func (s *Session) sendMultiExpire(ids []string) ([]int, error) {
	// cache inactive duration as string
	seconds := strconv.Itoa(int(s.inactiveDuration.Seconds()))

	// get one connection from pool
	c := s.redis.Pool().Get()

	// init multi command
	c.Send("MULTI")

	// send expire command for all members
	for _, id := range ids {
		c.Send("EXPIRE", s.redis.AddPrefix(id), seconds)
	}

	// execute command
	r, err := c.Do("EXEC")
	if err != nil {
		return make([]int, 0), err
	}

	// close connection
	if err := c.Close(); err != nil {
		return make([]int, 0), err
	}

	values, err := s.redis.Values(r)
	if err != nil {
		return make([]int, 0), err
	}

	res := make([]int, len(values))
	for i, value := range values {
		res[i], err = s.redis.Int(value)
		if err != nil {
			return make([]int, 0), err
		}

	}

	return res, nil
}

// Status returns the current status a key from system
func (s *Session) Status(ids ...string) ([]Event, error) {
	// get one connection from pool
	c := s.redis.Pool().Get()

	// init multi command
	c.Send("MULTI")

	// send expire command for all members
	for _, id := range ids {
		c.Send("EXISTS", s.redis.AddPrefix(id))
	}

	// execute command
	r, err := c.Do("EXEC")
	if err != nil {
		return make([]Event, 0), err
	}

	// close connection
	if err := c.Close(); err != nil {
		return make([]Event, 0), err
	}

	values, err := s.redis.Values(r)
	if err != nil {
		return make([]Event, 0), err
	}

	res := make([]Event, len(values))
	for i, value := range values {
		status, err := s.redis.Int(value)
		if err != nil {
			return make([]Event, 0), err
		}

		res[i] = Event{
			Id:     ids[i],
			Status: Status(status),
		}
	}

	return res, nil
}

// createEvent Creates the event with the required properties
func (s *Session) createEvent(n gredis.PMessage) Event {
	e := Event{}

	switch n.Pattern {
	case s.becameOfflinePattern:
		e.Id = string(n.Data[len(RedisencePrefix)+1:])
		e.Status = Offline
	case s.becameOnlinePattern:
		e.Id = string(n.Data[len(RedisencePrefix)+1:])
		e.Status = Online
	default:
		//ignore other events
	}

	return e
}

// ListenStatusChanges pubscribes to the redis and
// gets online and offline status changes from it
func (s *Session) ListenStatusChanges(events chan Event) {
	psc := s.redis.CreatePubSubConn()

	psc.PSubscribe(s.becameOnlinePattern, s.becameOfflinePattern)

	var wg sync.WaitGroup
	wg.Add(1)

	go func() {
		defer wg.Done()
		for {
			switch n := psc.Receive().(type) {
			case gredis.PMessage:
				events <- s.createEvent(n)
			case error:
				fmt.Printf("error: %v\n", n)
				return
			}
		}
	}()

	// avoid lock
	go func() {
		wg.Wait()
		psc.PUnsubscribe(s.becameOfflinePattern, s.becameOnlinePattern)
		psc.Close()
		events <- Event{Status: Closed}
	}()
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	"github.com/boltdb/bolt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"time"
	"unicode"
)

const (
	TK_UNDEFINED = iota
	TK_LS
	TK_CLEAR
	TK_HELP
	TK_REPLAY
	TK_SHOW
	TK_NUM
	TK_STRING
	TK_COUNT
	TK_USERS
	TK_BIND
	TK_INFO
	TK_LPAREN
	TK_RPAREN
	TK_COMMA
	TK_DURATION
	TK_EOF
)

var cmds = map[string]int{
	"ls":    TK_LS,
	"help":  TK_HELP,
	"clear": TK_CLEAR,

	"users": TK_USERS,
	"info":  TK_INFO,

	"bind":     TK_BIND,
	"count":    TK_COUNT,
	"duration": TK_DURATION,
	"show":     TK_SHOW,
	"replay":   TK_REPLAY,
}

type token struct {
	typ     int
	literal string
	num     int
}

// set ts=8
var help = `REDO Replay Tool
Commands:

list all database files(sorted by time):
> ls
> help		-- print this text
> clear 	-- clear all bindings

Global operations to file:
> users(1)	-- print all users of file#1
> info(2)	-- print summary of file#2

Bind Operations to user:
> bind(1, 1234)	-- all operations below are binded to a file#1 & user#1234
> count			-- print number of records of the user
> show			-- show all elements of the user
> replay("mongodb://172.17.42.1/mydb")	-- replay all changes of the user

Bind operations to duration:
> duration("2015-10-28T14:53:27", "2015-10-29T14:53:27")
(all operations below are binded to this duration)
> count		-- print number of records of the user in this duration
> show		-- show all elements of the user in this duration
> replay("mongodb://172.17.42.1/mydb")	-- replay all changes of the user in this duration
`

type ToolBox struct {
	dbs          []*bolt.DB // all opened boltdb
	fileid       int        // current selected db
	userid       int        // current selected userid
	duration_a   time.Time
	duration_b   time.Time
	duration_set bool
	mgo_url      string
	cmd_reader   *bytes.Buffer // cmds
}

func (t *ToolBox) init(dir string) {
	t.cmd_clear()
	files, err := filepath.Glob(dir + "/*.RDO")
	if err != nil {
		log.Println(err)
		os.Exit(-1)
	}

	for _, file := range files {
		db, err := bolt.Open(file, 0600, nil)
		if err != nil {
			log.Println(err)
			continue
		}
		t.dbs = append(t.dbs, db)
	}
}

//////////////////////////////////////////
// parser
func (t *ToolBox) next() *token {
	var r rune
	var err error
	for {
		r, _, err = t.cmd_reader.ReadRune()
		if err == io.EOF {
			return &token{typ: TK_EOF}
		} else if unicode.IsSpace(r) {
			continue
		}
		break
	}

	if unicode.IsLetter(r) {
		var runes []rune
		for {
			runes = append(runes, r)
			r, _, err = t.cmd_reader.ReadRune()
			if err == io.EOF {
				break
			} else if unicode.IsLetter(r) {
				continue
			} else {
				t.cmd_reader.UnreadRune()
				break
			}
		}

		t := &token{}
		t.literal = string(runes)
		t.typ = cmds[t.literal]
		return t
	} else if r == '"' { // quoted string
		var runes []rune
		for {
			r, _, err = t.cmd_reader.ReadRune()
			if err == io.EOF {
				break
			} else if r != '"' { // read until '"'
				runes = append(runes, r)
				continue
			} else {
				break
			}
		}
		t := &token{}
		t.literal = string(runes)
		t.typ = TK_STRING
		return t
	} else if unicode.IsDigit(r) {
		var runes []rune
		for {
			runes = append(runes, r)
			r, _, err = t.cmd_reader.ReadRune()
			if err == io.EOF {
				break
			} else if unicode.IsDigit(r) {
				continue
			} else {
				t.cmd_reader.UnreadRune()
				break
			}
		}

		t := &token{}
		t.num, _ = strconv.Atoi(string(runes))
		t.typ = TK_NUM
		return t
	} else if r == '(' {
		return &token{typ: TK_LPAREN}
	} else if r == ')' {
		return &token{typ: TK_RPAREN}
	} else if r == ',' {
		return &token{typ: TK_COMMA}
	}
	return &token{}
}

func (t *ToolBox) match(typ int) *token {
	tk := t.next()
	if tk.typ != typ {
		panic("syntax error")
	}
	return tk
}

func (t *ToolBox) parse_exec(cmd string) {
	defer func() {
		if x := recover(); x != nil {
			fmt.Println(x, cmd)
		}
	}()
	t.cmd_reader = bytes.NewBufferString(cmd)
	tk := t.next()
	switch tk.typ {
	case TK_LS:
		t.cmd_ls()
	case TK_HELP:
		t.cmd_help()
	case TK_CLEAR:
		t.cmd_clear()

	case TK_USERS:
		t.cmd_users()
	case TK_INFO:
		t.cmd_info()

	case TK_DURATION:
		t.cmd_duration()
	case TK_BIND:
		t.cmd_bind()
	case TK_COUNT:
		t.cmd_count()
	case TK_SHOW:
		t.cmd_show()
	case TK_REPLAY:
		t.cmd_replay()
	default:
		fmt.Println("unkown command:", cmd)
	}
}
<commit_msg>update<commit_after>package main

import (
	"bytes"
	"fmt"
	"github.com/boltdb/bolt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"time"
	"unicode"
)

const (
	TK_UNDEFINED = iota
	TK_LS
	TK_CLEAR
	TK_HELP
	TK_REPLAY
	TK_SHOW
	TK_NUM
	TK_STRING
	TK_COUNT
	TK_USERS
	TK_BIND
	TK_INFO
	TK_LPAREN
	TK_RPAREN
	TK_COMMA
	TK_DURATION
	TK_EOF
)

var cmds = map[string]int{
	"ls":    TK_LS,
	"help":  TK_HELP,
	"clear": TK_CLEAR,

	"users": TK_USERS,
	"info":  TK_INFO,

	"bind":     TK_BIND,
	"count":    TK_COUNT,
	"duration": TK_DURATION,
	"show":     TK_SHOW,
	"replay":   TK_REPLAY,
}

type token struct {
	typ     int
	literal string
	num     int
}

// set ts=8
var help = `REDO Replay Tool
Commands:

list all database files(sorted by time):
> ls
> help		-- print this text
> clear 	-- clear all bindings

Global operations to file:
> users(1)	-- print all users of file#1
> info(2)	-- print summary of file#2

Bind Operations to user:
> bind(1, 1234)	-- all operations below are binded to a file#1 & user#1234
> count			-- print number of records of the user
> show			-- show all elements of the user
> replay("mongodb://172.17.42.1/mydb")	-- replay all changes of the user

Bind operations to duration:
> duration("2015-10-28T14:53:27", "2015-10-29T14:53:27")
(all operations below are binded to this duration)
> count		-- print number of records of the user in this duration
> show		-- show all elements of the user in this duration
> replay("mongodb://172.17.42.1/mydb")	-- replay all changes of the user in this duration
`

type ToolBox struct {
	dbs          []*bolt.DB // all opened boltdb
	fileid       int        // current selected db
	userid       int        // current selected userid
	duration_a   time.Time
	duration_b   time.Time
	duration_set bool
	mgo_url      string
	cmd_reader   *bytes.Buffer // cmds
}

func (t *ToolBox) init(dir string) {
	t.cmd_clear()
	files, err := filepath.Glob(dir + "/*.RDO")
	if err != nil {
		log.Println(err)
		os.Exit(-1)
	}

	for _, file := range files {
		db, err := bolt.Open(file, 0600, &bolt.Options{Timeout: 1 * time.Second})
		if err != nil {
			log.Println(err)
			continue
		}
		t.dbs = append(t.dbs, db)
	}
}

//////////////////////////////////////////
// parser
func (t *ToolBox) next() *token {
	var r rune
	var err error
	for {
		r, _, err = t.cmd_reader.ReadRune()
		if err == io.EOF {
			return &token{typ: TK_EOF}
		} else if unicode.IsSpace(r) {
			continue
		}
		break
	}

	if unicode.IsLetter(r) {
		var runes []rune
		for {
			runes = append(runes, r)
			r, _, err = t.cmd_reader.ReadRune()
			if err == io.EOF {
				break
			} else if unicode.IsLetter(r) {
				continue
			} else {
				t.cmd_reader.UnreadRune()
				break
			}
		}

		t := &token{}
		t.literal = string(runes)
		t.typ = cmds[t.literal]
		return t
	} else if r == '"' { // quoted string
		var runes []rune
		for {
			r, _, err = t.cmd_reader.ReadRune()
			if err == io.EOF {
				break
			} else if r != '"' { // read until '"'
				runes = append(runes, r)
				continue
			} else {
				break
			}
		}
		t := &token{}
		t.literal = string(runes)
		t.typ = TK_STRING
		return t
	} else if unicode.IsDigit(r) {
		var runes []rune
		for {
			runes = append(runes, r)
			r, _, err = t.cmd_reader.ReadRune()
			if err == io.EOF {
				break
			} else if unicode.IsDigit(r) {
				continue
			} else {
				t.cmd_reader.UnreadRune()
				break
			}
		}

		t := &token{}
		t.num, _ = strconv.Atoi(string(runes))
		t.typ = TK_NUM
		return t
	} else if r == '(' {
		return &token{typ: TK_LPAREN}
	} else if r == ')' {
		return &token{typ: TK_RPAREN}
	} else if r == ',' {
		return &token{typ: TK_COMMA}
	}
	return &token{}
}

func (t *ToolBox) match(typ int) *token {
	tk := t.next()
	if tk.typ != typ {
		panic("syntax error")
	}
	return tk
}

func (t *ToolBox) parse_exec(cmd string) {
	defer func() {
		if x := recover(); x != nil {
			fmt.Println(x, cmd)
		}
	}()
	t.cmd_reader = bytes.NewBufferString(cmd)
	tk := t.next()
	switch tk.typ {
	case TK_LS:
		t.cmd_ls()
	case TK_HELP:
		t.cmd_help()
	case TK_CLEAR:
		t.cmd_clear()

	case TK_USERS:
		t.cmd_users()
	case TK_INFO:
		t.cmd_info()

	case TK_DURATION:
		t.cmd_duration()
	case TK_BIND:
		t.cmd_bind()
	case TK_COUNT:
		t.cmd_count()
	case TK_SHOW:
		t.cmd_show()
	case TK_REPLAY:
		t.cmd_replay()
	default:
		fmt.Println("unkown command:", cmd)
	}
}
<|endoftext|>


<commit_before>package redbutton

//go:generate stringer -type=Button

import (
	"errors"
	"time"

	"github.com/karalabe/hid"
)

const (
	vendor       = 0x1d34
	product      = 0x000d
	PollInterval = 200 * time.Millisecond
)

type Button int

const (
	Unknown Button = iota
	Closed
	Pressed
	Armed
)

func State(dev *hid.Device) (Button, error) {
	buf := make([]byte, 8)
	buf[0] = 0x01
	buf[7] = 0x02

	if _, err := dev.Write(buf); err != nil {
		return Unknown, err
	}

	if _, err := dev.Read(buf); err != nil {
		return Unknown, err
	}

	if buf[7] != 0x03 {
		return Unknown, nil
	}

	return Button(buf[0] & 0x03), nil
}

func Poll(dev *hid.Device, d time.Duration) <-chan Button {
	if d == 0 {
		d = PollInterval
	}
	ch := make(chan Button)
	go func() {
		prev := Unknown
		tick := time.NewTicker(d)
		defer tick.Stop()
		defer close(ch)
		for range tick.C {
			state, err := State(dev)
			if err != nil {
				return
			}
			if state != prev {
				ch <- state
				prev = state
			}
		}
	}()
	return ch
}

func Open() (*hid.Device, error) {
	devs := hid.Enumerate(vendor, product)
	if len(devs) == 0 {
		return nil, errors.New("not found")
	}
	return devs[0].Open()
}
<commit_msg>Prepend report number (0)<commit_after>package redbutton

//go:generate stringer -type=Button

import (
	"errors"
	"time"

	"github.com/karalabe/hid"
)

const (
	vendor       = 0x1d34
	product      = 0x000d
	PollInterval = 200 * time.Millisecond
)

type Button int

const (
	Unknown Button = iota
	Closed
	Pressed
	Armed
)

func State(dev *hid.Device) (Button, error) {
	buf := []byte{0, 0, 0, 0, 0, 0, 0, 0, 2}

	if _, err := dev.Write(buf); err != nil {
		return Unknown, err
	}

	if _, err := dev.Read(buf[:8]); err != nil {
		return Unknown, err
	}

	return Button(buf[0] & 0x03), nil
}

func Poll(dev *hid.Device, d time.Duration) <-chan Button {
	if d == 0 {
		d = PollInterval
	}
	ch := make(chan Button)
	go func() {
		prev := Unknown
		tick := time.NewTicker(d)
		defer tick.Stop()
		defer close(ch)
		for range tick.C {
			state, err := State(dev)
			if err != nil {
				return
			}
			if state != prev {
				ch <- state
				prev = state
			}
		}
	}()
	return ch
}

func Open() (*hid.Device, error) {
	devs := hid.Enumerate(vendor, product)
	if len(devs) == 0 {
		return nil, errors.New("not found")
	}
	return devs[0].Open()
}
<|endoftext|>


<commit_before>package sshclient

import (
	"fmt"
	"github.com/eaciit/errorlib"
	// "io"
	// "os"
	// "log"
	"strings"
)

const (
	LIST             = "ls -l %s"
	LIST_PARAM       = "ls -l %s | awk '{ print $1,\"||\",$2,\"||\",$3,\"||\",$4,\"||\",$5,\"||\",$6,\"||\",$7,\"||\",$8,\"||\",$9,$10,$11}'"
	SEARCH           = "ls -l -R %s | grep %s"
	SEARCH_PARAM     = "ls -l -R %s | grep %s | awk '{ print $1,\"||\",$2,\"||\",$3,\"||\",$4,\"||\",$5,\"||\",$6,\"||\",$7,\"||\",$8,\"||\",$9,$10,$11}'"
	MKDIR            = "mkdir -m %s %s"
	REMOVE           = "rm -f %s"
	REMOVE_RECURSIVE = "rm -R -f %s"
	RENAME           = "mv %s %s"
	MKFILE           = "echo \"%s\" > %s"
	CHMOD            = "chmod %v %v"
	CHOWN            = "chwon %v:%v %v"
	CHOWN_RECURSIVE  = "chwon -R %v:%v %v"
)

func List(s SshSetting, path string, isParseble bool) (string, error) {
	if path == "" {
		return "", errorlib.Error("", "", "LIST", "Path is Undivined")
	}

	cmd := ""

	if isParseble {
		cmd = fmt.Sprintf(LIST_PARAM, path)
	} else {
		cmd = fmt.Sprintf(LIST, path)
	}

	res, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		e = errorlib.Error("", "", "LIST", e.Error())
	}

	startStr := strings.Index(res, "\n")

	return res[startStr:], e
}

func Search(s SshSetting, path string, isParseble bool, search string) (string, error) {
	if path == "" {
		return "", errorlib.Error("", "", "SEARCH", "Path is Undivined")
	}

	if search == "" {
		return "", errorlib.Error("", "", "SEARCH", "Search param is undivined")
	}

	cmd := ""

	if isParseble {
		cmd = fmt.Sprintf(SEARCH_PARAM, path, search)
	} else {
		cmd = fmt.Sprintf(SEARCH_PARAM, path, search)
	}

	res, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		e = errorlib.Error("", "", "LIST", e.Error())
	}

	return res, e
}

func MakeDir(s SshSetting, path string, permission string) error {
	if path == "" {
		return errorlib.Error("", "", "MAKEDIR", "Path is Undivined")
	}

	if permission == "" {
		permission = "755"
	}

	cmd := fmt.Sprintf(MKDIR, permission, path)
	_, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		e = errorlib.Error("", "", "MAKEDIR", e.Error())
	}

	return e
}

func Rename(s SshSetting, oldPath string, newPath string) error {
	if oldPath == "" {
		return errorlib.Error("", "", "RENAME", "Old Path is Undivined")
	}

	if newPath == "" {
		return errorlib.Error("", "", "RENAME", "New Path is Undivined")
	}

	cmd := fmt.Sprintf(RENAME, oldPath, newPath)
	_, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		e = errorlib.Error("", "", "RENAME", e.Error())
	}

	return e
}

func Remove(s SshSetting, recursive bool, paths ...string) map[string]error {
	var es map[string]error

	if len(paths) < 1 {
		es[""] = errorlib.Error("", "", "REMOVE", "Paths is Undivined")
		return es
	}

	for _, path := range paths {
		cmd := ""
		if recursive {
			cmd = fmt.Sprintf(REMOVE_RECURSIVE, path)
		} else {
			cmd = fmt.Sprintf(REMOVE, path)
		}

		_, e := s.GetOutputCommandSsh(cmd)

		if e != nil {
			if es == nil {
				es = map[string]error{}
			}
			es[path] = errorlib.Error("", "", "REMOVE", e.Error())
		}
	}
	return es
}

func MakeFile(s SshSetting, content string, path string, permission string, format bool) error {
	if path == "" {
		return errorlib.Error("", "", "MAKEFILE", "Path is Undivined")
	}

	cmd := fmt.Sprintf(MKFILE, content, path)
	_, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		return errorlib.Error("", "", "MAKEFILE", e.Error())
	}

	if permission == "" {
		permission = "755"
	}

	e = Chmod(s, path, permission, format)

	if e != nil {
		return errorlib.Error("", "", "MAKEFILE", e.Error())
	}

	return e
}

func constructPermission(strPermission string) (result string, err error) {
	permission_map := map[string]string{
		"rwx": "7",
		"rw-": "6",
		"r-x": "5",
		"r--": "4",
		"-wx": "3",
		"-w-": "2",
		"--x": "1",
		"---": "0",
	}

	if len(strPermission) == 6 {
		owner := permission_map[strPermission[:3]]
		group := permission_map[strPermission[3:6]]
		other := permission_map[strPermission[6:]]

		result = owner + group + other
	} else {
		err = errorlib.Error("", "", "Construct Permission", "The permission is not valid")
	}

	return
}

func Chmod(s SshSetting, path string, permission string, format bool) (e error) {
	if format {
		permission, e = constructPermission(permission)
		if e != nil {
			return errorlib.Error("", "", "CHMOD", e.Error())
		}
	}

	if path == "" {
		return errorlib.Error("", "", "CHMOD", "Path is Undivined")
	}

	if permission == "" {
		return errorlib.Error("", "", "CHMOD", "Permission is Undivined")
	}

	cmd := fmt.Sprintf(CHMOD, permission, path)
	_, e = s.GetOutputCommandSsh(cmd)

	if e != nil {
		return errorlib.Error("", "", "CHMOD", e.Error())
	}

	return e
}

func Chown(s SshSetting, path string, user string, group string, recursive bool) error {
	if path == "" {
		return errorlib.Error("", "", "CHOWN", "Path is Undivined")
	}

	if user == "" {
		return errorlib.Error("", "", "CHOWN", "User is Undivined")
	}

	if group == "" {
		return errorlib.Error("", "", "CHOWN", "Group is Undivined")
	}

	cmd := ""

	if recursive {
		cmd = fmt.Sprintf(CHOWN_RECURSIVE, user, group, path)
	} else {
		cmd = fmt.Sprintf(CHOWN, user, group, path)
	}

	_, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		return errorlib.Error("", "", "CHOWN", e.Error())
	}

	return e
}

/*func UploadFile(s SshSetting, content io.Reader, size int64, filename string, destination string) error {
	if destination == "" {
		return errorlib.Error("", "", "UPLOAD_FILE", "Destination is Undivined")
	}

	e := s.SshCopyByFile(content, size, os.FileMode.ModeAppend, filename, destination)

	if e != nil {
		e = errorlib.Error("", "", "UPLOAD_FILE", e.Error())
	}

	return e
}*/
<commit_msg>bug fixing for chmod<commit_after>package sshclient

import (
	"fmt"
	"github.com/eaciit/errorlib"
	// "io"
	// "os"
	// "log"
	"strings"
)

const (
	LIST             = "ls -l %s"
	LIST_PARAM       = "ls -l %s | awk '{ print $1,\"||\",$2,\"||\",$3,\"||\",$4,\"||\",$5,\"||\",$6,\"||\",$7,\"||\",$8,\"||\",$9,$10,$11}'"
	SEARCH           = "ls -l -R %s | grep %s"
	SEARCH_PARAM     = "ls -l -R %s | grep %s | awk '{ print $1,\"||\",$2,\"||\",$3,\"||\",$4,\"||\",$5,\"||\",$6,\"||\",$7,\"||\",$8,\"||\",$9,$10,$11}'"
	MKDIR            = "mkdir -m %s %s"
	REMOVE           = "rm -f %s"
	REMOVE_RECURSIVE = "rm -R -f %s"
	RENAME           = "mv %s %s"
	MKFILE           = "echo \"%s\" > %s"
	CHMOD            = "chmod %v %v"
	CHOWN            = "chwon %v:%v %v"
	CHOWN_RECURSIVE  = "chwon -R %v:%v %v"
)

func List(s SshSetting, path string, isParseble bool) (string, error) {
	if path == "" {
		return "", errorlib.Error("", "", "LIST", "Path is Undivined")
	}

	cmd := ""

	if isParseble {
		cmd = fmt.Sprintf(LIST_PARAM, path)
	} else {
		cmd = fmt.Sprintf(LIST, path)
	}

	res, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		e = errorlib.Error("", "", "LIST", e.Error())
	}

	startStr := strings.Index(res, "\n")

	return res[startStr:], e
}

func Search(s SshSetting, path string, isParseble bool, search string) (string, error) {
	if path == "" {
		return "", errorlib.Error("", "", "SEARCH", "Path is Undivined")
	}

	if search == "" {
		return "", errorlib.Error("", "", "SEARCH", "Search param is undivined")
	}

	cmd := ""

	if isParseble {
		cmd = fmt.Sprintf(SEARCH_PARAM, path, search)
	} else {
		cmd = fmt.Sprintf(SEARCH_PARAM, path, search)
	}

	res, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		e = errorlib.Error("", "", "LIST", e.Error())
	}

	return res, e
}

func MakeDir(s SshSetting, path string, permission string) error {
	if path == "" {
		return errorlib.Error("", "", "MAKEDIR", "Path is Undivined")
	}

	if permission == "" {
		permission = "755"
	}

	cmd := fmt.Sprintf(MKDIR, permission, path)
	_, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		e = errorlib.Error("", "", "MAKEDIR", e.Error())
	}

	return e
}

func Rename(s SshSetting, oldPath string, newPath string) error {
	if oldPath == "" {
		return errorlib.Error("", "", "RENAME", "Old Path is Undivined")
	}

	if newPath == "" {
		return errorlib.Error("", "", "RENAME", "New Path is Undivined")
	}

	cmd := fmt.Sprintf(RENAME, oldPath, newPath)
	_, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		e = errorlib.Error("", "", "RENAME", e.Error())
	}

	return e
}

func Remove(s SshSetting, recursive bool, paths ...string) map[string]error {
	var es map[string]error

	if len(paths) < 1 {
		es[""] = errorlib.Error("", "", "REMOVE", "Paths is Undivined")
		return es
	}

	for _, path := range paths {
		cmd := ""
		if recursive {
			cmd = fmt.Sprintf(REMOVE_RECURSIVE, path)
		} else {
			cmd = fmt.Sprintf(REMOVE, path)
		}

		_, e := s.GetOutputCommandSsh(cmd)

		if e != nil {
			if es == nil {
				es = map[string]error{}
			}
			es[path] = errorlib.Error("", "", "REMOVE", e.Error())
		}
	}
	return es
}

func MakeFile(s SshSetting, content string, path string, permission string, format bool) error {
	if path == "" {
		return errorlib.Error("", "", "MAKEFILE", "Path is Undivined")
	}

	cmd := fmt.Sprintf(MKFILE, content, path)
	_, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		return errorlib.Error("", "", "MAKEFILE", e.Error())
	}

	if permission == "" {
		permission = "755"
	}

	e = Chmod(s, path, permission, format)

	if e != nil {
		return errorlib.Error("", "", "MAKEFILE", e.Error())
	}

	return e
}

func constructPermission(strPermission string) (result string, err error) {
	permission_map := map[string]string{
		"rwx": "7",
		"rw-": "6",
		"r-x": "5",
		"r--": "4",
		"-wx": "3",
		"-w-": "2",
		"--x": "1",
		"---": "0",
	}

	if len(strPermission) == 9 {
		owner := permission_map[strPermission[:3]]
		group := permission_map[strPermission[3:6]]
		other := permission_map[strPermission[6:]]

		result = owner + group + other
	} else {
		err = errorlib.Error("", "", "Construct Permission", "The permission is not valid")
	}

	return
}

func Chmod(s SshSetting, path string, permission string, format bool) (e error) {
	if format {
		permission, e = constructPermission(permission)
		if e != nil {
			return errorlib.Error("", "", "CHMOD", e.Error())
		}
	}

	if path == "" {
		return errorlib.Error("", "", "CHMOD", "Path is Undivined")
	}

	if permission == "" {
		return errorlib.Error("", "", "CHMOD", "Permission is Undivined")
	}

	cmd := fmt.Sprintf(CHMOD, permission, path)
	_, e = s.GetOutputCommandSsh(cmd)

	if e != nil {
		return errorlib.Error("", "", "CHMOD", e.Error())
	}

	return e
}

func Chown(s SshSetting, path string, user string, group string, recursive bool) error {
	if path == "" {
		return errorlib.Error("", "", "CHOWN", "Path is Undivined")
	}

	if user == "" {
		return errorlib.Error("", "", "CHOWN", "User is Undivined")
	}

	if group == "" {
		return errorlib.Error("", "", "CHOWN", "Group is Undivined")
	}

	cmd := ""

	if recursive {
		cmd = fmt.Sprintf(CHOWN_RECURSIVE, user, group, path)
	} else {
		cmd = fmt.Sprintf(CHOWN, user, group, path)
	}

	_, e := s.GetOutputCommandSsh(cmd)

	if e != nil {
		return errorlib.Error("", "", "CHOWN", e.Error())
	}

	return e
}

/*func UploadFile(s SshSetting, content io.Reader, size int64, filename string, destination string) error {
	if destination == "" {
		return errorlib.Error("", "", "UPLOAD_FILE", "Destination is Undivined")
	}

	e := s.SshCopyByFile(content, size, os.FileMode.ModeAppend, filename, destination)

	if e != nil {
		e = errorlib.Error("", "", "UPLOAD_FILE", e.Error())
	}

	return e
}*/
<|endoftext|>


<commit_before>package repository

import (
	"time"

	"github.com/lib/pq"
	"github.com/syou6162/go-active-learning/lib/model"
)

func (r *repository) UpdateOrCreateReferringTweets(e *model.Example) error {
	if e.ReferringTweets == nil || len(*e.ReferringTweets) == 0 {
		return nil
	}

	tmp, err := r.FindExampleByUlr(e.Url)
	if err != nil {
		return err
	}
	id := tmp.Id

	for _, t := range *e.ReferringTweets {
		t.ExampleId = id
		if _, err = r.db.NamedExec(`
INSERT INTO tweet
( example_id,  created_at,  id_str,  full_text,  favorite_count,  retweet_count,  lang,  screen_name,  name,  profile_image_url,  label)
VALUES
(:example_id, :created_at, :id_str, :full_text, :favorite_count, :retweet_count, :lang, :screen_name, :name, :profile_image_url, :label)
ON CONFLICT (example_id, id_str)
DO UPDATE SET
favorite_count = :favorite_count,  retweet_count = :retweet_count, label = :label
;`, t); err != nil {
			return err
		}
	}
	return nil
}

func (r *repository) UpdateTweetLabel(exampleId int, idStr string, label model.LabelType) error {
	if _, err := r.db.Exec(`UPDATE tweet SET label = $1, updated_at = $2 WHERE example_id = $3 AND id_str = $4;`, label, time.Now(), exampleId, idStr); err != nil {
		return err
	}
	return nil
}

func (r *repository) SearchReferringTweetsList(examples model.Examples) (map[int]model.ReferringTweets, error) {
	referringTweetsByExampleId := make(map[int]model.ReferringTweets)

	referringTweets := model.ReferringTweets{}
	exampleIds := make([]int, 0)
	for _, e := range examples {
		exampleIds = append(exampleIds, e.Id)
	}

	query := `SELECT * FROM tweet WHERE example_id = ANY($1) AND label != -1 ORDER BY favorite_count DESC;`
	err := r.db.Select(&referringTweets, query, pq.Array(exampleIds))
	if err != nil {
		return referringTweetsByExampleId, err
	}

	for _, t := range referringTweets {
		referringTweetsByExampleId[t.ExampleId] = append(referringTweetsByExampleId[t.ExampleId], t)
	}
	return referringTweetsByExampleId, nil
}

func (r *repository) FindReferringTweets(e *model.Example) (model.ReferringTweets, error) {
	referringTweets := model.ReferringTweets{}

	query := `SELECT * FROM tweet WHERE example_id = $1 AND label != -1 ORDER BY favorite_count DESC;`
	err := r.db.Select(&referringTweets, query, e.Id)
	if err != nil {
		return referringTweets, err
	}
	return referringTweets, nil
}
<commit_msg>update_atカラムは存在しなかった<commit_after>package repository

import (
	"github.com/lib/pq"
	"github.com/syou6162/go-active-learning/lib/model"
)

func (r *repository) UpdateOrCreateReferringTweets(e *model.Example) error {
	if e.ReferringTweets == nil || len(*e.ReferringTweets) == 0 {
		return nil
	}

	tmp, err := r.FindExampleByUlr(e.Url)
	if err != nil {
		return err
	}
	id := tmp.Id

	for _, t := range *e.ReferringTweets {
		t.ExampleId = id
		if _, err = r.db.NamedExec(`
INSERT INTO tweet
( example_id,  created_at,  id_str,  full_text,  favorite_count,  retweet_count,  lang,  screen_name,  name,  profile_image_url,  label)
VALUES
(:example_id, :created_at, :id_str, :full_text, :favorite_count, :retweet_count, :lang, :screen_name, :name, :profile_image_url, :label)
ON CONFLICT (example_id, id_str)
DO UPDATE SET
favorite_count = :favorite_count,  retweet_count = :retweet_count, label = :label
;`, t); err != nil {
			return err
		}
	}
	return nil
}

func (r *repository) UpdateTweetLabel(exampleId int, idStr string, label model.LabelType) error {
	if _, err := r.db.Exec(`UPDATE tweet SET label = $1 WHERE example_id = $2 AND id_str = $3;`, label, exampleId, idStr); err != nil {
		return err
	}
	return nil
}

func (r *repository) SearchReferringTweetsList(examples model.Examples) (map[int]model.ReferringTweets, error) {
	referringTweetsByExampleId := make(map[int]model.ReferringTweets)

	referringTweets := model.ReferringTweets{}
	exampleIds := make([]int, 0)
	for _, e := range examples {
		exampleIds = append(exampleIds, e.Id)
	}

	query := `SELECT * FROM tweet WHERE example_id = ANY($1) AND label != -1 ORDER BY favorite_count DESC;`
	err := r.db.Select(&referringTweets, query, pq.Array(exampleIds))
	if err != nil {
		return referringTweetsByExampleId, err
	}

	for _, t := range referringTweets {
		referringTweetsByExampleId[t.ExampleId] = append(referringTweetsByExampleId[t.ExampleId], t)
	}
	return referringTweetsByExampleId, nil
}

func (r *repository) FindReferringTweets(e *model.Example) (model.ReferringTweets, error) {
	referringTweets := model.ReferringTweets{}

	query := `SELECT * FROM tweet WHERE example_id = $1 AND label != -1 ORDER BY favorite_count DESC;`
	err := r.db.Select(&referringTweets, query, e.Id)
	if err != nil {
		return referringTweets, err
	}
	return referringTweets, nil
}
<|endoftext|>


<commit_before>// Package repl implements an event loop aware REPL (read-eval-print loop)
// for otto.
package repl // import "fknsrs.biz/p/ottoext/repl"

import (
	"fmt"
	"io"
	"strings"

	"fknsrs.biz/p/ottoext/loop"
	"fknsrs.biz/p/ottoext/loop/looptask"
	"github.com/robertkrimen/otto"
	"github.com/robertkrimen/otto/parser"
	"gopkg.in/readline.v1"
)

// Run creates a REPL with the default prompt and no prelude.
func Run(l *loop.Loop) error {
	return RunWithPromptAndPrelude(l, "", "")
}

// RunWithPrompt runs a REPL with the given prompt and no prelude.
func RunWithPrompt(l *loop.Loop, prompt string) error {
	return RunWithPromptAndPrelude(l, prompt, "")
}

// RunWithPrelude runs a REPL with the default prompt and the given prelude.
func RunWithPrelude(l *loop.Loop, prelude string) error {
	return RunWithPromptAndPrelude(l, "", prelude)
}

// RunWithPromptAndPrelude runs a REPL with the given prompt and prelude.
func RunWithPromptAndPrelude(l *loop.Loop, prompt, prelude string) error {
	if prompt == "" {
		prompt = ">"
	}

	prompt = strings.Trim(prompt, " ")
	prompt += " "

	rl, err := readline.New(prompt)
	if err != nil {
		return err
	}

	l.VM().Set("console", map[string]interface{}{
		"log": func(c otto.FunctionCall) otto.Value {
			s := make([]string, len(c.ArgumentList))
			for i := 0; i < len(c.ArgumentList); i++ {
				s[i] = c.Argument(i).String()
			}

			rl.Stdout().Write([]byte(strings.Join(s, " ") + "\n"))
			rl.Refresh()

			return otto.UndefinedValue()
		},
		"warn": func(c otto.FunctionCall) otto.Value {
			s := make([]string, len(c.ArgumentList))
			for i := 0; i < len(c.ArgumentList); i++ {
				s[i] = c.Argument(i).String()
			}

			rl.Stderr().Write([]byte(strings.Join(s, " ") + "\n"))
			rl.Refresh()

			return otto.UndefinedValue()
		},
	})

	if prelude != "" {
		if _, err := io.Copy(rl.Stderr(), strings.NewReader(prelude+"\n")); err != nil {
			return err
		}

		rl.Refresh()
	}

	var d []string

	for {
		ll, err := rl.Readline()
		if err != nil {
			if err == readline.ErrInterrupt {
				if d != nil {
					d = nil

					rl.SetPrompt(prompt)
					rl.Refresh()

					continue
				}

				break
			}

			return err
		}

		if len(d) == 0 && ll == "" {
			continue
		}

		d = append(d, ll)
		s := strings.Join(d, "\n")

		if _, err := parser.ParseFile(nil, "repl", s, 0); err != nil {
			rl.SetPrompt(strings.Repeat(" ", len(prompt)))
		} else {
			rl.SetPrompt(prompt)

			d = nil

			t := looptask.NewEvalTask(s)
			// don't report errors to the loop - this lets us handle them and
			// resume normal operation
			t.SoftError = true
			l.Add(t)
			l.Ready(t)

			v, err := <-t.Value, <-t.Error
			if err != nil {
				if oerr, ok := err.(*otto.Error); ok {
					io.Copy(rl.Stdout(), strings.NewReader(oerr.String()))
				} else {
					io.Copy(rl.Stdout(), strings.NewReader(err.Error()))
				}
			} else {
				f, err := format(v, 80, 2, 5)
				if err != nil {
					panic(err)
				}

				rl.Stdout().Write([]byte(f + "\n"))
			}
		}

		rl.Refresh()
	}

	return rl.Close()
}

func inspect(v otto.Value, width, indent int) string {
	switch {
	case v.IsBoolean(), v.IsNull(), v.IsNumber(), v.IsString(), v.IsUndefined(), v.IsNaN():
		return fmt.Sprintf("%s%q", strings.Repeat("  ", indent), v.String())
	default:
		return ""
	}
}
<commit_msg>move to start of line before printing things in the repl<commit_after>// Package repl implements an event loop aware REPL (read-eval-print loop)
// for otto.
package repl // import "fknsrs.biz/p/ottoext/repl"

import (
	"fmt"
	"io"
	"strings"

	"fknsrs.biz/p/ottoext/loop"
	"fknsrs.biz/p/ottoext/loop/looptask"
	"github.com/robertkrimen/otto"
	"github.com/robertkrimen/otto/parser"
	"gopkg.in/readline.v1"
)

// Run creates a REPL with the default prompt and no prelude.
func Run(l *loop.Loop) error {
	return RunWithPromptAndPrelude(l, "", "")
}

// RunWithPrompt runs a REPL with the given prompt and no prelude.
func RunWithPrompt(l *loop.Loop, prompt string) error {
	return RunWithPromptAndPrelude(l, prompt, "")
}

// RunWithPrelude runs a REPL with the default prompt and the given prelude.
func RunWithPrelude(l *loop.Loop, prelude string) error {
	return RunWithPromptAndPrelude(l, "", prelude)
}

// RunWithPromptAndPrelude runs a REPL with the given prompt and prelude.
func RunWithPromptAndPrelude(l *loop.Loop, prompt, prelude string) error {
	if prompt == "" {
		prompt = ">"
	}

	prompt = strings.Trim(prompt, " ")
	prompt += " "

	rl, err := readline.New(prompt)
	if err != nil {
		return err
	}

	l.VM().Set("console", map[string]interface{}{
		"log": func(c otto.FunctionCall) otto.Value {
			s := make([]string, len(c.ArgumentList))
			for i := 0; i < len(c.ArgumentList); i++ {
				s[i] = c.Argument(i).String()
			}

			rl.Stdout().Write([]byte(strings.Join(s, " ") + "\n"))
			rl.Refresh()

			return otto.UndefinedValue()
		},
		"warn": func(c otto.FunctionCall) otto.Value {
			s := make([]string, len(c.ArgumentList))
			for i := 0; i < len(c.ArgumentList); i++ {
				s[i] = c.Argument(i).String()
			}

			rl.Stderr().Write([]byte(strings.Join(s, " ") + "\n"))
			rl.Refresh()

			return otto.UndefinedValue()
		},
	})

	if prelude != "" {
		if _, err := io.Copy(rl.Stderr(), strings.NewReader(prelude+"\n")); err != nil {
			return err
		}

		rl.Refresh()
	}

	var d []string

	for {
		ll, err := rl.Readline()
		if err != nil {
			if err == readline.ErrInterrupt {
				if d != nil {
					d = nil

					rl.SetPrompt(prompt)
					rl.Refresh()

					continue
				}

				break
			}

			return err
		}

		if len(d) == 0 && ll == "" {
			continue
		}

		d = append(d, ll)
		s := strings.Join(d, "\n")

		if _, err := parser.ParseFile(nil, "repl", s, 0); err != nil {
			rl.SetPrompt(strings.Repeat(" ", len(prompt)))
		} else {
			rl.SetPrompt(prompt)

			d = nil

			t := looptask.NewEvalTask(s)
			// don't report errors to the loop - this lets us handle them and
			// resume normal operation
			t.SoftError = true
			l.Add(t)
			l.Ready(t)

			v, err := <-t.Value, <-t.Error
			if err != nil {
				if oerr, ok := err.(*otto.Error); ok {
					io.Copy(rl.Stdout(), strings.NewReader(oerr.String()))
				} else {
					io.Copy(rl.Stdout(), strings.NewReader(err.Error()))
				}
			} else {
				f, err := format(v, 80, 2, 5)
				if err != nil {
					panic(err)
				}

				rl.Stdout().Write([]byte("\r" + f + "\n"))
			}
		}

		rl.Refresh()
	}

	return rl.Close()
}

func inspect(v otto.Value, width, indent int) string {
	switch {
	case v.IsBoolean(), v.IsNull(), v.IsNumber(), v.IsString(), v.IsUndefined(), v.IsNaN():
		return fmt.Sprintf("%s%q", strings.Repeat("  ", indent), v.String())
	default:
		return ""
	}
}
<|endoftext|>


<commit_before>package repo

import (
	"os"
	"path"
	"strings"

	"pkg.re/essentialkaos/ek.v8/fmtc"
	"pkg.re/essentialkaos/ek.v8/fsutil"

	"github.com/gongled/vgrepo/meta"
)

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

type VRepository struct {
	*meta.VMetadata
}

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

func getVersion(version string) string {
	ver := "latest"

	if version != "" {
		ver = version
	}

	return ver
}

func getBoxFormat(name string, version string) string {
	return fmtc.Sprintf("%s-%s.box", name, getVersion(version))
}

func (r *VRepository) BaseRepo() string {
	return path.Join(r.StoragePath, r.Name)
}

func (r *VRepository) DirRepo() string {
	return path.Join(r.BaseRepo(), "boxes")
}

func (r *VRepository) PathRepo(version string) string {
	return path.Join(r.DirRepo(), getBoxFormat(r.Name, version))
}

func (r *VRepository) URLRepo(version string) string {
	return fmtc.Sprintf("%s/%s/%s/%s",
		strings.Trim(r.StorageURL, "/"),
		r.Name,
		"boxes",
		getBoxFormat(r.Name, version),
	)
}

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

func (r *VRepository) HasBox(version string) bool {
	return fsutil.IsExist(r.PathRepo(version))
}

func (r *VRepository) IsExist(version string) bool {
	return r.HasMeta() && r.HasBox(version)
}

func (r *VRepository) AddBox(src string) error {
	var err error

	//if !fsutil.IsExist(src) {
	//	err := fmtc.Errorf("Unable to read file %s\n", src)
	//	return err
	//}

	//if r.Meta.IsEmptyMeta() {
	//	r.Meta.Description = metadata.Description
	//}

	fmtc.Printf("Reading metadata...\n")
	r.Name = "qweqwe"
	fmtc.Println(r.Name)

	//if fsutil.IsExist(ver) {
	//	err := fmtc.Errorf("File %s is already exist", ver)
	//	return err
	//}
	//
	//if !fsutil.IsDir(basedir) {
	//	err := os.MkdirAll(basedir, 0755)
	//	return err
	//}

	//err = fsutil2.CopyFile(src, dst)

	return err
}

func (r *VRepository) DeleteBox(version string) error {
	ver := getVersion(version)

	fmtc.Println(ver)

	return nil
}

func (r *VRepository) Destroy() error {
	err := os.RemoveAll(r.BaseRepo())

	return err
}

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

func NewRepository(storagePath string, storageUrl string, name string) *VRepository {
	r := meta.NewMetadata(
		storagePath,
		storageUrl,
		name,
		"",
		make([]*meta.VMetadataVersion, 0))

	m := &VRepository{r}

	if m.HasMeta() {
		// TODO: remove returning value *VMetadataRepository
		m.VMetadata, _ = m.ReadMeta()
	}

	return m
}

// ////////////////////////////////////////////////////////////////////////////////// //
<commit_msg>Removed newline symbols from Error structs.<commit_after>package repo

import (
	"os"
	"path"
	"strings"

	"pkg.re/essentialkaos/ek.v8/fmtc"
	"pkg.re/essentialkaos/ek.v8/fsutil"

	"github.com/gongled/vgrepo/meta"
)

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

type VRepository struct {
	*meta.VMetadata
}

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

func getVersion(version string) string {
	ver := "latest"

	if version != "" {
		ver = version
	}

	return ver
}

func getBoxFormat(name string, version string) string {
	return fmtc.Sprintf("%s-%s.box", name, getVersion(version))
}

func (r *VRepository) BaseRepo() string {
	return path.Join(r.StoragePath, r.Name)
}

func (r *VRepository) DirRepo() string {
	return path.Join(r.BaseRepo(), "boxes")
}

func (r *VRepository) PathRepo(version string) string {
	return path.Join(r.DirRepo(), getBoxFormat(r.Name, version))
}

func (r *VRepository) URLRepo(version string) string {
	return fmtc.Sprintf("%s/%s/%s/%s",
		strings.Trim(r.StorageURL, "/"),
		r.Name,
		"boxes",
		getBoxFormat(r.Name, version),
	)
}

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

func (r *VRepository) HasBox(version string) bool {
	return fsutil.IsExist(r.PathRepo(version))
}

func (r *VRepository) IsExist(version string) bool {
	return r.HasMeta() && r.HasBox(version)
}

func (r *VRepository) AddBox(src string) error {
	var err error

	//if !fsutil.IsExist(src) {
	//	err := fmtc.Errorf("Unable to read file %s", src)
	//	return err
	//}

	//if r.Meta.IsEmptyMeta() {
	//	r.Meta.Description = metadata.Description
	//}

	fmtc.Printf("Reading metadata...\n")
	r.Name = "qweqwe"
	fmtc.Println(r.Name)

	//if fsutil.IsExist(ver) {
	//	err := fmtc.Errorf("File %s is already exist", ver)
	//	return err
	//}
	//
	//if !fsutil.IsDir(basedir) {
	//	err := os.MkdirAll(basedir, 0755)
	//	return err
	//}

	//err = fsutil2.CopyFile(src, dst)

	return err
}

func (r *VRepository) DeleteBox(version string) error {
	ver := getVersion(version)

	fmtc.Println(ver)

	return nil
}

func (r *VRepository) Destroy() error {
	err := os.RemoveAll(r.BaseRepo())

	return err
}

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

func NewRepository(storagePath string, storageUrl string, name string) *VRepository {
	r := meta.NewMetadata(
		storagePath,
		storageUrl,
		name,
		"",
		make([]*meta.VMetadataVersion, 0))

	m := &VRepository{r}

	if m.HasMeta() {
		// TODO: remove returning value *VMetadataRepository
		m.VMetadata, _ = m.ReadMeta()
	}

	return m
}

// ////////////////////////////////////////////////////////////////////////////////// //
<|endoftext|>


<commit_before>package main

import (
	"io"
	"net/http"

	k8sapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	k8sclient "github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	restful "github.com/emicklei/go-restful"
)

type SelfRegisteringResource interface {
	Register(string)
}

type PingResource struct {
}

func (r PingResource) Register(prefix string) {
	ws := new(restful.WebService)
	ws.Path(prefix + "/ping")
	ws.Route(ws.GET("/").To(pong))
	restful.Add(ws)
}

func pong(req *restful.Request, resp *restful.Response) {
	io.WriteString(resp, "pong")
}

type ContainerResource struct {
	client *k8sclient.Client
}

func (r ContainerResource) Register(prefix string) {
	ws := new(restful.WebService)
	ws.Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON)
	ws.Path(prefix)
	ws.Route(ws.GET("/minions").To(r.minions).Writes(k8sapi.NodeList{}))
	ws.Route(ws.GET("/pods").To(r.pods).Writes(k8sapi.PodList{}))
	ws.Route(ws.GET("/{namespace}/pods").To(r.pods).Writes(k8sapi.PodList{}))
	ws.Route(ws.GET("/services").To(r.services).Writes(k8sapi.ServiceList{}))
	ws.Route(ws.GET("/{namespace}/services").To(r.services).Writes(k8sapi.ServiceList{}))
	ws.Route(ws.GET("/replicationControllers").To(r.replicationControllers).Writes(k8sapi.ReplicationControllerList{}))
	ws.Route(ws.GET("/{namespace}/replicationControllers").To(r.replicationControllers).Writes(k8sapi.ReplicationControllerList{}))
	restful.Add(ws)
}

func (r ContainerResource) minions(request *restful.Request, response *restful.Response) {
	if minions, err := r.client.Nodes().List(); err != nil {
		response.AddHeader("Content-Type", "text/plain")
		response.WriteErrorString(http.StatusInternalServerError, err.Error())
	} else {
		response.WriteEntity(minions.Items)
	}
}

func (r ContainerResource) pods(request *restful.Request, response *restful.Response) {
	namespace := request.PathParameter("namespace")
	if pods, err := r.client.Pods(namespace).List(labels.Everything()); err != nil {
		response.AddHeader("Content-Type", "text/plain")
		response.WriteErrorString(http.StatusInternalServerError, err.Error())
	} else {
		response.WriteEntity(pods.Items)
	}
}

func (r ContainerResource) services(request *restful.Request, response *restful.Response) {
	namespace := request.PathParameter("namespace")
	if services, err := r.client.Services(namespace).List(labels.Everything()); err != nil {
		response.AddHeader("Content-Type", "text/plain")
		response.WriteErrorString(http.StatusInternalServerError, err.Error())
	} else {
		response.WriteEntity(services.Items)
	}
}

func (r ContainerResource) replicationControllers(request *restful.Request, response *restful.Response) {
	namespace := request.PathParameter("namespace")
	if rcs, err := r.client.ReplicationControllers(namespace).List(labels.Everything()); err != nil {
		response.AddHeader("Content-Type", "text/plain")
		response.WriteErrorString(http.StatusInternalServerError, err.Error())
	} else {
		response.WriteEntity(rcs.Items)
	}
}
<commit_msg>Remove unused REST endpoints now we straight proxy everything<commit_after><|endoftext|>


<commit_before>package router

import (
	"contract"
	"fmt"
	"io/ioutil"
	"net/http"
)

type Router struct {
	Contract *contract.Contract
}

func NewRouter(c *contract.Contract) *Router {
	r := new(Router)
	r.Contract = c
	return r
}

func (r Router) RegistAndRun() {
	http.HandleFunc(r.Contract.URL, r.Handle)
	fmt.Println("Running...")
	http.ListenAndServe(":8080", nil)
}

func (r Router) Handle(w http.ResponseWriter, req *http.Request) {
	switch req.Method {
	case "GET":
		r.Get(w, req)
	case "POST":
		r.Post(w, req)
	case "OPTIONS":
		r.Options(w, req)
	}
}

func (r Router) Options(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	/*
		w.Header().Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "authorization,cache-control,orgid,pragma,userid")
	*/

	fmt.Fprintln(w, "")
}

func (r Router) Get(w http.ResponseWriter, req *http.Request) {
	// fmt.Fprintf(w, "Hello Get\n")

	fmt.Fprintln(w, r.Contract.Get.String())
}

// Need to validate the output and expected output
func (r Router) Post(w http.ResponseWriter, req *http.Request) {
	// fmt.Fprintf(w, "Hello Post\n")

	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		panic(err)
	}
	//expected := r.Contract.Post.Encode()
	expected := r.Contract.Post
	// fmt.Fprintln(w, r.Contract.Post.String())
	fmt.Fprintln(w, string(body) == expected)
	//fmt.Printf("%s\n%s\n", string(body), expected)
}
<commit_msg>make router regist multiple urls and handlers<commit_after>package router

import (
	"contract"
	"fmt"
	"io/ioutil"
	"net/http"
)

type Router struct {
	ContractList *contract.ContractList
}

func NewRouter(c *contract.ContractList) *Router {
	r := new(Router)
	r.ContractList = c
	return r
}

func (r Router) RegistAndRun() {
	for _, c := range r.ContractList.Contracts {
		ctr := new(contract.Contract)
		ctr.URL = c.URL
		ctr.Get = c.Get
		ctr.Post = c.Post

		http.HandleFunc(ctr.URL, func(w http.ResponseWriter, req *http.Request) {
			switch req.Method {
			case "GET":
				func(w http.ResponseWriter, req *http.Request) {
					fmt.Fprintln(w, ctr.Get.String())
				}(w, req)
			case "POST":
				func(w http.ResponseWriter, req *http.Request) {
					body, err := ioutil.ReadAll(req.Body)
					if err != nil {
						panic(err)
					}
					expected := ctr.Post
					fmt.Fprintln(w, string(body) == expected)
				}(w, req)
			case "OPTIONS":
				func(w http.ResponseWriter, req *http.Request) {
					w.Header().Set("Access-Control-Allow-Origin", "*")
					fmt.Fprintln(w, "")
				}(w, req)
			}
		})
	}

	fmt.Println("Running...")
	http.ListenAndServe(":8080", nil)
}
<|endoftext|>