<commit_before>package main

import (
	"fmt"
	"github.com/orvice/shadowsocks-go/mu/user"
	ss "github.com/shadowsocks/shadowsocks-go/shadowsocks"
	"os"
	"strconv"
	"time"
	muconfig "github.com/orvice/shadowsocks-go/mu/config"
)

var configFile string
var config *ss.Config

func boot() {
	var err error

	// log.SetOutput(os.Stdout)

	err = InitMySqlClient()
	if err != nil {
		Log.Error(err)
		os.Exit(0)
	}
	client := user.GetClient()
	users, err := client.GetUsers()
	if err != nil {
		Log.Error(err)
		os.Exit(0)
	}
	Log.Info(len(users))
	// clear storage
	storage.ClearAll()
	bootUsers(users)
	time.Sleep(muconfig.Conf.Base.CheckTime * time.Second)

	go func() {
		for {
			// check users
			users, err = client.GetUsers()
			if err != nil {
				Log.Error(err)
				// os.Exit(0)
			}
			checkUsers(users)
			Log.Info("check finish...")
			time.Sleep(muconfig.Conf.Base.CheckTime * time.Second)
			Log.Info("wake up...")
		}
	}()
	waitSignal()
}

// 第一次启动
func bootUsers(users []user.User) {
	for _, user := range users {
		Log.Info(user.GetUserInfo())
		err := storage.StoreUser(user.GetUserInfo())
		if err != nil {
			Log.Error(err)
		}
		go runWithCustomMethod(user)
	}
}

// check users
func checkUsers(users []user.User) {
	for _, user := range users {
		Log.Debug("check user for ", user.GetPort())

		isExists, err := storage.Exists(user)
		if err != nil {
			Log.Error(err)
			continue
		}
		if !isExists {
			Log.Info("new user to run", user)
			err := storage.StoreUser(user.GetUserInfo())
			if err != nil {
				Log.Error(err)
			}
			go runWithCustomMethod(user)
			continue
		}
		if !user.IsEnable() {
			Log.Info("user would be disable,port:  ", user.GetPort())
			passwdManager.del(strconv.Itoa(user.GetPort()))
			err := storage.Del(user)
			if err != nil {
				Log.Error(err)
			}
			continue
		}
		sUser, err := storage.GetUserInfo(user)
		if err != nil {
			Log.Error(err)
			continue
		}
		if sUser.Passwd != user.GetPasswd() || sUser.Method != user.GetMethod() {
			Log.Info(fmt.Sprintf("user port [%v] passwd or method change ,restart user...", user.GetPort()))
			passwdManager.del(strconv.Itoa(user.GetPort()))
			go runWithCustomMethod(user)
		}
	}
}
<commit_msg>bug fix<commit_after>package main

import (
	"fmt"
	muconfig "github.com/orvice/shadowsocks-go/mu/config"
	"github.com/orvice/shadowsocks-go/mu/user"
	ss "github.com/shadowsocks/shadowsocks-go/shadowsocks"
	"os"
	"strconv"
	"time"
)

var configFile string
var config *ss.Config

func boot() {
	var err error

	// log.SetOutput(os.Stdout)

	err = InitMySqlClient()
	if err != nil {
		Log.Error(err)
		os.Exit(0)
	}
	client := user.GetClient()
	users, err := client.GetUsers()
	if err != nil {
		Log.Error(err)
		os.Exit(0)
	}
	Log.Info(len(users))
	// clear storage
	storage.ClearAll()
	bootUsers(users)
	time.Sleep(muconfig.Conf.Base.CheckTime * time.Second)

	go func() {
		for {
			// check users
			users, err = client.GetUsers()
			if err != nil {
				Log.Error(err)
				// os.Exit(0)
			}
			checkUsers(users)
			Log.Info("check finish...")
			time.Sleep(muconfig.Conf.Base.CheckTime * time.Second)
			Log.Info("wake up...")
		}
	}()
	waitSignal()
}

// 第一次启动
func bootUsers(users []user.User) {
	for _, user := range users {
		Log.Info(user.GetUserInfo())
		err := storage.StoreUser(user.GetUserInfo())
		if err != nil {
			Log.Error(err)
		}
		go runWithCustomMethod(user)
	}
}

// check users
func checkUsers(users []user.User) {
	for _, user := range users {
		Log.Debug("check user for ", user.GetPort())

		isExists, err := storage.Exists(user)
		if err != nil {
			Log.Error(err)
			continue
		}
		if !isExists && user.IsEnable() {
			Log.Info("new user to run", user)
			err := storage.StoreUser(user.GetUserInfo())
			if err != nil {
				Log.Error(err)
			}
			go runWithCustomMethod(user)
			continue
		}
		if !user.IsEnable() {
			Log.Info("user would be disable,port:  ", user.GetPort())
			passwdManager.del(strconv.Itoa(user.GetPort()))
			err := storage.Del(user)
			if err != nil {
				Log.Error(err)
			}
			continue
		}
		sUser, err := storage.GetUserInfo(user)
		if err != nil {
			Log.Error(err)
			continue
		}
		if sUser.Passwd != user.GetPasswd() || sUser.Method != user.GetMethod() {
			Log.Info(fmt.Sprintf("user port [%v] passwd or method change ,restart user...", user.GetPort()))
			passwdManager.del(strconv.Itoa(user.GetPort()))
			go runWithCustomMethod(user)
		}
	}
}
<|endoftext|>


<commit_before>package syncmap

import (
	"errors"
	"time"
)

var (
	TimeError = errors.New("text")
)

//timeEntity has value, create time, duration, update time.
type timeEntity struct {
	entity interface{}
	dtime  time.Duration
	ctime  time.Time
	utime  time.Time
}

//TimeEntity is a interface for timeEntity
type TimeEntity interface {
	IsResident() (b bool)
	IsDie() (b bool)
	BeUsed() (err error)
	Update(value interface{}) (err error)
	ChangeDur(d time.Duration) (err error)
	Value() (val interface{}, err error)
}

//NewTimeEntity init a timeEntity, used value and duration.
func NewTimeEntity(value interface{}, d time.Duration) TimeEntity {
	return &timeEntity{
		entity: value,
		dtime:  d,
		ctime:  time.Now(),
		//utime:  time.Time{},
	}
}

func (t *timeEntity) IsResident() (b bool) {
	if t.dtime == 0 {
		b = true
	} else {
		b = false
	}
	return
}

func (t *timeEntity) IsDie() (b bool) {
	if t.IsResident() {
		b = false
	} else {
		curTime := time.Now()
		var mTime time.Time
		if t.utime.IsZero() {
			mTime = t.ctime
		} else {
			mTime = t.utime
		}
		if curTime.Sub(mTime) >= t.dtime {
			b = true
		} else {
			b = false
		}
	}
	return
}

func (t *timeEntity) BeUsed() (err error) {
	if !t.IsResident() {
		t.utime = time.Now()
	}
	return
}

func (t *timeEntity) Update(value interface{}) (err error) {
	t.entity = value
	t.BeUsed()
	return
}

func (t *timeEntity) ChangeDur(d time.Duration) (err error) {
	t.dtime = d
	t.BeUsed()
	return
}

func (t *timeEntity) Value() (val interface{}, err error) {
	val = t.entity
	return
}
<commit_msg>timeEntity.go add get duration time function, any used the entity must change update time.<commit_after>package syncmap

import (
	"errors"
	"time"
)

var (
	TimeError = errors.New("text")
)

//timeEntity has value, create time, duration, update time.
type timeEntity struct {
	entity interface{}
	dtime  time.Duration
	ctime  time.Time
	utime  time.Time
}

//TimeEntity is a interface for timeEntity
type TimeEntity interface {
	IsResident() (b bool)
	IsDie() (b bool)
	BeUsed() (err error)
	Update(value interface{}) (err error)
	ChangeDur(d time.Duration) (err error)
	Value() (val interface{}, err error)
	Dtime() (dtime time.Duration)
}

//NewTimeEntity init a timeEntity, used value and duration.
func NewTimeEntity(value interface{}, d time.Duration) TimeEntity {
	return &timeEntity{
		entity: value,
		dtime:  d,
		ctime:  time.Now(),
		//utime:  time.Time{},
	}
}

func (t *timeEntity) IsResident() (b bool) {
	if t.dtime == 0 {
		b = true
	} else {
		b = false
	}
	return
}

func (t *timeEntity) IsDie() (b bool) {
	if t.IsResident() {
		b = false
	} else {
		curTime := time.Now()
		var mTime time.Time
		if t.utime.IsZero() {
			mTime = t.ctime
		} else {
			mTime = t.utime
		}
		if curTime.Sub(mTime) >= t.dtime {
			b = true
		} else {
			b = false
		}
	}
	return
}

func (t *timeEntity) BeUsed() (err error) {
	/*if !t.IsResident() {
		t.utime = time.Now()
	}*/
	t.utime = time.Now()
	return
}

func (t *timeEntity) Update(value interface{}) (err error) {
	t.entity = value
	t.BeUsed()
	return
}

func (t *timeEntity) ChangeDur(d time.Duration) (err error) {
	t.dtime = d
	t.BeUsed()
	return
}

func (t *timeEntity) Value() (val interface{}, err error) {
	val = t.entity
	t.BeUsed()
	return
}

func (t *timeEntity) Dtime() (dtime time.Duration) {
	return t.dtime
}
<|endoftext|>


<commit_before><commit_msg>Fix variable shadowing bug<commit_after><|endoftext|>


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

package remote

import (
	"context"
	"sync"

	"github.com/go-kit/kit/log"
	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/config"
	"github.com/prometheus/prometheus/pkg/labels"
	"github.com/prometheus/prometheus/storage"
)

// Callback func that return the oldest timestamp stored in a storage.
type startTimeCallback func() (int64, error)

// Storage represents all the remote read and write endpoints.  It implements
// storage.Storage.
type Storage struct {
	logger log.Logger
	mtx    sync.RWMutex

	// For writes
	queues []*QueueManager

	// For reads
	queryables             []storage.Queryable
	localStartTimeCallback startTimeCallback
}

// NewStorage returns a remote.Storage.
func NewStorage(l log.Logger, stCallback startTimeCallback) *Storage {
	if l == nil {
		l = log.NewNopLogger()
	}
	return &Storage{logger: l, localStartTimeCallback: stCallback}
}

// ApplyConfig updates the state as the new config requires.
func (s *Storage) ApplyConfig(conf *config.Config) error {
	s.mtx.Lock()
	defer s.mtx.Unlock()

	// Update write queues

	newQueues := []*QueueManager{}
	// TODO: we should only stop & recreate queues which have changes,
	// as this can be quite disruptive.
	for i, rwConf := range conf.RemoteWriteConfigs {
		c, err := NewClient(i, &ClientConfig{
			URL:              rwConf.URL,
			Timeout:          rwConf.RemoteTimeout,
			HTTPClientConfig: rwConf.HTTPClientConfig,
		})
		if err != nil {
			return err
		}
		newQueues = append(newQueues, NewQueueManager(
			s.logger,
			config.DefaultQueueConfig,
			conf.GlobalConfig.ExternalLabels,
			rwConf.WriteRelabelConfigs,
			c,
		))
	}

	for _, q := range s.queues {
		q.Stop()
	}

	s.queues = newQueues
	for _, q := range s.queues {
		q.Start()
	}

	// Update read clients

	s.queryables = make([]storage.Queryable, 0, len(conf.RemoteReadConfigs))
	for i, rrConf := range conf.RemoteReadConfigs {
		c, err := NewClient(i, &ClientConfig{
			URL:              rrConf.URL,
			Timeout:          rrConf.RemoteTimeout,
			HTTPClientConfig: rrConf.HTTPClientConfig,
		})
		if err != nil {
			return err
		}

		var q storage.Queryable
		q = QueryableClient(c)
		q = ExternablLabelsHandler(q, conf.GlobalConfig.ExternalLabels)
		if len(rrConf.RequiredMatchers) > 0 {
			q = RequiredMatchersFilter(q, labelsToEqualityMatchers(rrConf.RequiredMatchers))
		}
		if !rrConf.ReadRecent {
			q = PreferLocalStorageFilter(q, s.localStartTimeCallback)
		}
		s.queryables = append(s.queryables, q)
	}

	return nil
}

// StartTime implements the Storage interface.
func (s *Storage) StartTime() (int64, error) {
	return int64(model.Latest), nil
}

// Querier returns a storage.MergeQuerier combining the remote client queriers
// of each configured remote read endpoint.
func (s *Storage) Querier(ctx context.Context, mint, maxt int64) (storage.Querier, error) {
	s.mtx.Lock()
	queryables := s.queryables
	s.mtx.Unlock()

	queriers := make([]storage.Querier, 0, len(queryables))
	for _, queryable := range queryables {
		q, err := queryable.Querier(ctx, mint, maxt)
		if err != nil {
			return nil, err
		}
		queriers = append(queriers, q)
	}
	return storage.NewMergeQuerier(queriers), nil
}

// Close the background processing of the storage queues.
func (s *Storage) Close() error {
	s.mtx.Lock()
	defer s.mtx.Unlock()

	for _, q := range s.queues {
		q.Stop()
	}

	return nil
}

func labelsToEqualityMatchers(ls model.LabelSet) []*labels.Matcher {
	ms := make([]*labels.Matcher, 0, len(ls))
	for k, v := range ls {
		ms = append(ms, &labels.Matcher{
			Type:  labels.MatchEqual,
			Name:  string(k),
			Value: string(v),
		})
	}
	return ms
}
<commit_msg>fixed bug with initialization of queueconfig<commit_after>// Copyright 2017 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package remote

import (
	"context"
	"sync"

	"github.com/go-kit/kit/log"
	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/config"
	"github.com/prometheus/prometheus/pkg/labels"
	"github.com/prometheus/prometheus/storage"
)

// Callback func that return the oldest timestamp stored in a storage.
type startTimeCallback func() (int64, error)

// Storage represents all the remote read and write endpoints.  It implements
// storage.Storage.
type Storage struct {
	logger log.Logger
	mtx    sync.RWMutex

	// For writes
	queues []*QueueManager

	// For reads
	queryables             []storage.Queryable
	localStartTimeCallback startTimeCallback
}

// NewStorage returns a remote.Storage.
func NewStorage(l log.Logger, stCallback startTimeCallback) *Storage {
	if l == nil {
		l = log.NewNopLogger()
	}
	return &Storage{logger: l, localStartTimeCallback: stCallback}
}

// ApplyConfig updates the state as the new config requires.
func (s *Storage) ApplyConfig(conf *config.Config) error {
	s.mtx.Lock()
	defer s.mtx.Unlock()

	// Update write queues

	newQueues := []*QueueManager{}
	// TODO: we should only stop & recreate queues which have changes,
	// as this can be quite disruptive.
	for i, rwConf := range conf.RemoteWriteConfigs {
		c, err := NewClient(i, &ClientConfig{
			URL:              rwConf.URL,
			Timeout:          rwConf.RemoteTimeout,
			HTTPClientConfig: rwConf.HTTPClientConfig,
		})
		if err != nil {
			return err
		}
		newQueues = append(newQueues, NewQueueManager(
			s.logger,
			rwConf.QueueConfig,
			conf.GlobalConfig.ExternalLabels,
			rwConf.WriteRelabelConfigs,
			c,
		))
	}

	for _, q := range s.queues {
		q.Stop()
	}

	s.queues = newQueues
	for _, q := range s.queues {
		q.Start()
	}

	// Update read clients

	s.queryables = make([]storage.Queryable, 0, len(conf.RemoteReadConfigs))
	for i, rrConf := range conf.RemoteReadConfigs {
		c, err := NewClient(i, &ClientConfig{
			URL:              rrConf.URL,
			Timeout:          rrConf.RemoteTimeout,
			HTTPClientConfig: rrConf.HTTPClientConfig,
		})
		if err != nil {
			return err
		}

		var q storage.Queryable
		q = QueryableClient(c)
		q = ExternablLabelsHandler(q, conf.GlobalConfig.ExternalLabels)
		if len(rrConf.RequiredMatchers) > 0 {
			q = RequiredMatchersFilter(q, labelsToEqualityMatchers(rrConf.RequiredMatchers))
		}
		if !rrConf.ReadRecent {
			q = PreferLocalStorageFilter(q, s.localStartTimeCallback)
		}
		s.queryables = append(s.queryables, q)
	}

	return nil
}

// StartTime implements the Storage interface.
func (s *Storage) StartTime() (int64, error) {
	return int64(model.Latest), nil
}

// Querier returns a storage.MergeQuerier combining the remote client queriers
// of each configured remote read endpoint.
func (s *Storage) Querier(ctx context.Context, mint, maxt int64) (storage.Querier, error) {
	s.mtx.Lock()
	queryables := s.queryables
	s.mtx.Unlock()

	queriers := make([]storage.Querier, 0, len(queryables))
	for _, queryable := range queryables {
		q, err := queryable.Querier(ctx, mint, maxt)
		if err != nil {
			return nil, err
		}
		queriers = append(queriers, q)
	}
	return storage.NewMergeQuerier(queriers), nil
}

// Close the background processing of the storage queues.
func (s *Storage) Close() error {
	s.mtx.Lock()
	defer s.mtx.Unlock()

	for _, q := range s.queues {
		q.Stop()
	}

	return nil
}

func labelsToEqualityMatchers(ls model.LabelSet) []*labels.Matcher {
	ms := make([]*labels.Matcher, 0, len(ls))
	for k, v := range ls {
		ms = append(ms, &labels.Matcher{
			Type:  labels.MatchEqual,
			Name:  string(k),
			Value: string(v),
		})
	}
	return ms
}
<|endoftext|>


<commit_before><commit_msg>p1/main.go: Changed comment format.<commit_after><|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"github.com/urfave/cli"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"strings"
)

var HDHR_PORT int = 65001

func main() {
	app := cli.NewApp()
	app.Name = "hdhomerun"
	app.Usage = "Control the hdhomerun on your network"
	app.Commands = []cli.Command{
		{
			Name:    "discover",
			Aliases: []string{"d"},
			Usage:   "Discover HDHR devices on network",
			Action: func(c *cli.Context) error {
				discoverHDHR()
				return nil
			},
		},
		{
			Name:    "channels",
			Aliases: []string{"c"},
			Usage:   "Print out list of channels",
			Action: func(c *cli.Context) error {
				getChannels()
				return nil
			},
		},
	}

	app.Run(os.Args)
}

func discoverHDHR() string {
	// The discovery binary was discovered via tcpdump
	const discovery_bin = ("\x00\x02\x00\x0c\x01\x04\x00\x00\x00\x01" +
		"\x02\x04\xff\xff\xff\xff\x4e\x50\x7f\x35")

	// Setup socket that is going to send/receive discovery datagrams
	RAddr, _ := net.ResolveUDPAddr("udp", "192.168.174.255:65001")
	ServerAddr, _ := net.ResolveUDPAddr("udp", "192.168.174.168:")
	listen_conn, err := net.ListenUDP("udp", ServerAddr)

	if err != nil {
		fmt.Println("Error opening UDP socket: ", err)
		return ""
	}

	listen_conn.WriteTo([]byte(discovery_bin), RAddr)

	// Grab response for a buffer
	buf := make([]byte, 1024)
	for {
		_, addr, err := listen_conn.ReadFromUDP(buf)

		if err != nil {
			fmt.Println("Error reading from UDP socket: ", err)
		}
		return ""
		msg := "hdhomerun device %x found at %s\n"
		// e.g. "hdhomerun device 1322F2F9 found at 192.168.174.249"
		hdhr_ip := strings.Split(addr.String(), ":")[0]
		hdhr_dev_name := buf[12:16]

		fmt.Printf(msg, hdhr_dev_name, hdhr_ip)

		return hdhr_ip
	}
}

func getChannels() {
	hdhr_ip := discoverHDHR()

	lineup_url := "http://%s/lineup.json"
	resp, err := http.Get(fmt.Sprintf(lineup_url, hdhr_ip))

	if err != nil {
		fmt.Println("Error downloading lineup JSON: ", err)
		return
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	type Channel struct {
		GuideNumber string
		GuideName   string
		URL         string
	}

	var channels []Channel

	err = json.Unmarshal(body, &channels)
	if err != nil {
		fmt.Println("Error decoding JSON: ", err)
	}

	row := "%3s\t%-20s\t%s\n"
	for _, ch := range channels {
		fmt.Printf(row, ch.GuideNumber, ch.GuideName, ch.URL)
	}
}
<commit_msg>Had a return in the wrong place<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"github.com/urfave/cli"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"strings"
)

var HDHR_PORT int = 65001

func main() {
	app := cli.NewApp()
	app.Name = "hdhomerun"
	app.Usage = "Control the hdhomerun on your network"
	app.Commands = []cli.Command{
		{
			Name:    "discover",
			Aliases: []string{"d"},
			Usage:   "Discover HDHR devices on network",
			Action: func(c *cli.Context) error {
				discoverHDHR()
				return nil
			},
		},
		{
			Name:    "channels",
			Aliases: []string{"c"},
			Usage:   "Print out list of channels",
			Action: func(c *cli.Context) error {
				getChannels()
				return nil
			},
		},
	}

	app.Run(os.Args)
}

func discoverHDHR() string {
	// The discovery binary was discovered via tcpdump
	const discovery_bin = ("\x00\x02\x00\x0c\x01\x04\x00\x00\x00\x01" +
		"\x02\x04\xff\xff\xff\xff\x4e\x50\x7f\x35")

	// Setup socket that is going to send/receive discovery datagrams
	RAddr, _ := net.ResolveUDPAddr("udp", "192.168.174.255:65001")
	ServerAddr, _ := net.ResolveUDPAddr("udp", "192.168.174.168:")
	listen_conn, err := net.ListenUDP("udp", ServerAddr)

	if err != nil {
		fmt.Println("Error opening UDP socket: ", err)
		return ""
	}

	listen_conn.WriteTo([]byte(discovery_bin), RAddr)

	// Grab response for a buffer
	buf := make([]byte, 1024)
	for {
		_, addr, err := listen_conn.ReadFromUDP(buf)

		if err != nil {
			fmt.Println("Error reading from UDP socket: ", err)
			return ""
		}

		msg := "hdhomerun device %x found at %s\n"
		// e.g. "hdhomerun device 1322F2F9 found at 192.168.174.249"
		hdhr_ip := strings.Split(addr.String(), ":")[0]
		hdhr_dev_name := buf[12:16]

		fmt.Printf(msg, hdhr_dev_name, hdhr_ip)

		return hdhr_ip
	}
}

func getChannels() {
	hdhr_ip := discoverHDHR()

	lineup_url := "http://%s/lineup.json"
	resp, err := http.Get(fmt.Sprintf(lineup_url, hdhr_ip))

	if err != nil {
		fmt.Println("Error downloading lineup JSON: ", err)
		return
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	type Channel struct {
		GuideNumber string
		GuideName   string
		URL         string
	}

	var channels []Channel

	err = json.Unmarshal(body, &channels)
	if err != nil {
		fmt.Println("Error decoding JSON: ", err)
	}

	row := "%3s\t%-20s\t%s\n"
	for _, ch := range channels {
		fmt.Printf(row, ch.GuideNumber, ch.GuideName, ch.URL)
	}
}
<|endoftext|>


<commit_before>// Copyright 2015 Hajime Hoshi
//
// 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.

// +build example jsgo

package main

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"image"
	"image/color"
	_ "image/jpeg"
	"log"
	"math"
	"math/rand"
	"time"

	"github.com/hajimehoshi/ebiten"
	"github.com/hajimehoshi/ebiten/ebitenutil"
	"github.com/hajimehoshi/ebiten/examples/resources/images"
	"github.com/hajimehoshi/ebiten/inpututil"
)

var (
	windowDecorated = flag.Bool("windowdecorated", true, "whether the window is decorated")
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

const (
	initScreenWidth  = 320
	initScreenHeight = 240
	initScreenScale  = 2
)

var (
	gophersImage *ebiten.Image
	count        = 0
)

func createRandomIconImage() image.Image {
	const size = 32

	r := uint8(rand.Intn(0x100))
	g := uint8(rand.Intn(0x100))
	b := uint8(rand.Intn(0x100))
	img := image.NewNRGBA(image.Rect(0, 0, size, size))
	for j := 0; j < size; j++ {
		for i := 0; i < size; i++ {
			img.Pix[j*img.Stride+4*i] = r
			img.Pix[j*img.Stride+4*i+1] = g
			img.Pix[j*img.Stride+4*i+2] = b
			img.Pix[j*img.Stride+4*i+3] = uint8(float64(i+j) / float64(2*size) * 0xff)
		}
	}

	return img
}

var terminated = errors.New("terminated")

func update(screen *ebiten.Image) error {
	if inpututil.IsKeyJustPressed(ebiten.KeyQ) {
		return terminated
	}

	screenScale := ebiten.ScreenScale()
	d := int(32 / screenScale)
	screenWidth, screenHeight := screen.Size()
	fullscreen := ebiten.IsFullscreen()
	runnableInBackground := ebiten.IsRunnableInBackground()
	cursorVisible := ebiten.IsCursorVisible()
	vsyncEnabled := ebiten.IsVsyncEnabled()
	tps := ebiten.MaxTPS()

	if inpututil.IsKeyJustPressed(ebiten.KeyUp) {
		screenHeight += d
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyDown) {
		if 16 < screenHeight && d < screenHeight {
			screenHeight -= d
		}
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyLeft) {
		if 16 < screenWidth && d < screenWidth {
			screenWidth -= d
		}
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyRight) {
		screenWidth += d
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyS) {
		switch screenScale {
		case 0.75:
			screenScale = 1
		case 1:
			screenScale = 1.5
		case 1.5:
			screenScale = 2
		case 2:
			screenScale = 0.75
		default:
			panic("not reached")
		}
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyF) {
		fullscreen = !fullscreen
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyB) {
		runnableInBackground = !runnableInBackground
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyC) {
		cursorVisible = !cursorVisible
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyV) {
		vsyncEnabled = !vsyncEnabled
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyT) {
		switch tps {
		case ebiten.UncappedTPS:
			tps = 30
		case 30:
			tps = 60
		case 60:
			tps = 120
		case 120:
			tps = ebiten.UncappedTPS
		default:
			panic("not reached")
		}
	}

	ebiten.SetScreenSize(screenWidth, screenHeight)
	ebiten.SetScreenScale(screenScale)
	ebiten.SetFullscreen(fullscreen)
	ebiten.SetRunnableInBackground(runnableInBackground)
	ebiten.SetCursorVisible(cursorVisible)
	ebiten.SetVsyncEnabled(vsyncEnabled)
	ebiten.SetMaxTPS(tps)

	if inpututil.IsKeyJustPressed(ebiten.KeyI) {
		ebiten.SetWindowIcon([]image.Image{createRandomIconImage()})
	}

	count++

	if ebiten.IsDrawingSkipped() {
		return nil
	}

	screen.Fill(color.RGBA{0x80, 0x80, 0xc0, 0xff})
	w, h := gophersImage.Size()
	w2, h2 := screen.Size()
	op := &ebiten.DrawImageOptions{}
	op.GeoM.Translate(float64(-w+w2)/2, float64(-h+h2)/2)
	dx := math.Cos(2*math.Pi*float64(count)/360) * 10
	dy := math.Sin(2*math.Pi*float64(count)/360) * 10
	op.GeoM.Translate(dx, dy)
	screen.DrawImage(gophersImage, op)

	x, y := ebiten.CursorPosition()
	tpsStr := "Uncapped"
	if t := ebiten.MaxTPS(); t != ebiten.UncappedTPS {
		tpsStr = fmt.Sprintf("%d", t)
	}
	msg := fmt.Sprintf(`Press arrow keys to change the window size
Press S key to change the window scale
Press F key to switch the fullscreen state
Press B key to switch the run-in-background state
Press C key to switch the cursor visibility
Press I key to change the window icon
Press V key to switch vsync
Press T key to switch TPS (ticks per second)
Press Q key to quit
Cursor: (%d, %d)
TPS: Current: %0.2f / Max: %s
FPS: %0.2f`, x, y, ebiten.CurrentTPS(), tpsStr, ebiten.CurrentFPS())
	ebitenutil.DebugPrint(screen, msg)
	return nil
}

func main() {
	flag.Parse()

	fmt.Printf("Device scale factor: %0.2f\n", ebiten.DeviceScaleFactor())
	w, h := ebiten.ScreenSizeInFullscreen()
	fmt.Printf("Screen size in fullscreen: %d, %d\n", w, h)

	// Decode image from a byte slice instead of a file so that
	// this example works in any working directory.
	// If you want to use a file, there are some options:
	// 1) Use os.Open and pass the file to the image decoder.
	//    This is a very regular way, but doesn't work on browsers.
	// 2) Use ebitenutil.OpenFile and pass the file to the image decoder.
	//    This works even on browsers.
	// 3) Use ebitenutil.NewImageFromFile to create an ebiten.Image directly from a file.
	//    This also works on browsers.
	img, _, err := image.Decode(bytes.NewReader(images.Gophers_jpg))
	if err != nil {
		log.Fatal(err)
	}
	gophersImage, _ = ebiten.NewImageFromImage(img, ebiten.FilterDefault)

	ebiten.SetWindowIcon([]image.Image{createRandomIconImage()})

	ebiten.SetWindowDecorated(*windowDecorated)

	if err := ebiten.Run(update, initScreenWidth, initScreenHeight, initScreenScale, "Window Size (Ebiten Demo)"); err != nil && err != terminated {
		log.Fatal(err)
	}
}
<commit_msg>examples/windowsize: Bug fix: Strange delta of window size<commit_after>// Copyright 2015 Hajime Hoshi
//
// 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.

// +build example jsgo

package main

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"image"
	"image/color"
	_ "image/jpeg"
	"log"
	"math"
	"math/rand"
	"time"

	"github.com/hajimehoshi/ebiten"
	"github.com/hajimehoshi/ebiten/ebitenutil"
	"github.com/hajimehoshi/ebiten/examples/resources/images"
	"github.com/hajimehoshi/ebiten/inpututil"
)

var (
	windowDecorated = flag.Bool("windowdecorated", true, "whether the window is decorated")
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

const (
	initScreenWidth  = 320
	initScreenHeight = 240
	initScreenScale  = 2
)

var (
	gophersImage *ebiten.Image
	count        = 0
)

func createRandomIconImage() image.Image {
	const size = 32

	r := uint8(rand.Intn(0x100))
	g := uint8(rand.Intn(0x100))
	b := uint8(rand.Intn(0x100))
	img := image.NewNRGBA(image.Rect(0, 0, size, size))
	for j := 0; j < size; j++ {
		for i := 0; i < size; i++ {
			img.Pix[j*img.Stride+4*i] = r
			img.Pix[j*img.Stride+4*i+1] = g
			img.Pix[j*img.Stride+4*i+2] = b
			img.Pix[j*img.Stride+4*i+3] = uint8(float64(i+j) / float64(2*size) * 0xff)
		}
	}

	return img
}

var terminated = errors.New("terminated")

func update(screen *ebiten.Image) error {
	if inpututil.IsKeyJustPressed(ebiten.KeyQ) {
		return terminated
	}

	screenScale := ebiten.ScreenScale()
	const d = 16
	screenWidth, screenHeight := screen.Size()
	fullscreen := ebiten.IsFullscreen()
	runnableInBackground := ebiten.IsRunnableInBackground()
	cursorVisible := ebiten.IsCursorVisible()
	vsyncEnabled := ebiten.IsVsyncEnabled()
	tps := ebiten.MaxTPS()

	if inpututil.IsKeyJustPressed(ebiten.KeyUp) {
		screenHeight += d
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyDown) {
		if 16 < screenHeight && d < screenHeight {
			screenHeight -= d
		}
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyLeft) {
		if 16 < screenWidth && d < screenWidth {
			screenWidth -= d
		}
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyRight) {
		screenWidth += d
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyS) {
		switch screenScale {
		case 0.75:
			screenScale = 1
		case 1:
			screenScale = 1.5
		case 1.5:
			screenScale = 2
		case 2:
			screenScale = 0.75
		default:
			panic("not reached")
		}
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyF) {
		fullscreen = !fullscreen
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyB) {
		runnableInBackground = !runnableInBackground
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyC) {
		cursorVisible = !cursorVisible
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyV) {
		vsyncEnabled = !vsyncEnabled
	}
	if inpututil.IsKeyJustPressed(ebiten.KeyT) {
		switch tps {
		case ebiten.UncappedTPS:
			tps = 30
		case 30:
			tps = 60
		case 60:
			tps = 120
		case 120:
			tps = ebiten.UncappedTPS
		default:
			panic("not reached")
		}
	}

	ebiten.SetScreenSize(screenWidth, screenHeight)
	ebiten.SetScreenScale(screenScale)
	ebiten.SetFullscreen(fullscreen)
	ebiten.SetRunnableInBackground(runnableInBackground)
	ebiten.SetCursorVisible(cursorVisible)
	ebiten.SetVsyncEnabled(vsyncEnabled)
	ebiten.SetMaxTPS(tps)

	if inpututil.IsKeyJustPressed(ebiten.KeyI) {
		ebiten.SetWindowIcon([]image.Image{createRandomIconImage()})
	}

	count++

	if ebiten.IsDrawingSkipped() {
		return nil
	}

	screen.Fill(color.RGBA{0x80, 0x80, 0xc0, 0xff})
	w, h := gophersImage.Size()
	w2, h2 := screen.Size()
	op := &ebiten.DrawImageOptions{}
	op.GeoM.Translate(float64(-w+w2)/2, float64(-h+h2)/2)
	dx := math.Cos(2*math.Pi*float64(count)/360) * 10
	dy := math.Sin(2*math.Pi*float64(count)/360) * 10
	op.GeoM.Translate(dx, dy)
	screen.DrawImage(gophersImage, op)

	x, y := ebiten.CursorPosition()
	tpsStr := "Uncapped"
	if t := ebiten.MaxTPS(); t != ebiten.UncappedTPS {
		tpsStr = fmt.Sprintf("%d", t)
	}
	msg := fmt.Sprintf(`Press arrow keys to change the window size
Press S key to change the window scale
Press F key to switch the fullscreen state
Press B key to switch the run-in-background state
Press C key to switch the cursor visibility
Press I key to change the window icon
Press V key to switch vsync
Press T key to switch TPS (ticks per second)
Press Q key to quit
Cursor: (%d, %d)
TPS: Current: %0.2f / Max: %s
FPS: %0.2f`, x, y, ebiten.CurrentTPS(), tpsStr, ebiten.CurrentFPS())
	ebitenutil.DebugPrint(screen, msg)
	return nil
}

func main() {
	flag.Parse()

	fmt.Printf("Device scale factor: %0.2f\n", ebiten.DeviceScaleFactor())
	w, h := ebiten.ScreenSizeInFullscreen()
	fmt.Printf("Screen size in fullscreen: %d, %d\n", w, h)

	// Decode image from a byte slice instead of a file so that
	// this example works in any working directory.
	// If you want to use a file, there are some options:
	// 1) Use os.Open and pass the file to the image decoder.
	//    This is a very regular way, but doesn't work on browsers.
	// 2) Use ebitenutil.OpenFile and pass the file to the image decoder.
	//    This works even on browsers.
	// 3) Use ebitenutil.NewImageFromFile to create an ebiten.Image directly from a file.
	//    This also works on browsers.
	img, _, err := image.Decode(bytes.NewReader(images.Gophers_jpg))
	if err != nil {
		log.Fatal(err)
	}
	gophersImage, _ = ebiten.NewImageFromImage(img, ebiten.FilterDefault)

	ebiten.SetWindowIcon([]image.Image{createRandomIconImage()})

	ebiten.SetWindowDecorated(*windowDecorated)

	if err := ebiten.Run(update, initScreenWidth, initScreenHeight, initScreenScale, "Window Size (Ebiten Demo)"); err != nil && err != terminated {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package nsqd

import (
	"bufio"
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strconv"
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

func TestDiskQueue(t *testing.T) {
	l := newTestLogger(t)

	dqName := "test_disk_queue" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	dq := newDiskQueue(dqName, tmpDir, 1024, 4, 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), int64(0))

	msg := []byte("test")
	err = dq.Put(msg)
	equal(t, err, nil)
	equal(t, dq.Depth(), int64(1))

	msgOut := <-dq.ReadChan()
	equal(t, msgOut, msg)
}

func TestDiskQueueRoll(t *testing.T) {
	l := newTestLogger(t)
	dqName := "test_disk_queue_roll" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	msg := bytes.Repeat([]byte{0}, 10)
	ml := int64(len(msg))
	dq := newDiskQueue(dqName, tmpDir, 9*(ml+4), int32(ml), 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), int64(0))

	for i := 0; i < 10; i++ {
		err := dq.Put(msg)
		equal(t, err, nil)
		equal(t, dq.Depth(), int64(i+1))
	}

	equal(t, dq.(*diskQueue).writeFileNum, int64(1))
	equal(t, dq.(*diskQueue).writePos, int64(0))
}

func assertFileNotExist(t *testing.T, fn string) {
	f, err := os.OpenFile(fn, os.O_RDONLY, 0600)
	equal(t, f, (*os.File)(nil))
	equal(t, os.IsNotExist(err), true)
}

func TestDiskQueueEmpty(t *testing.T) {
	l := newTestLogger(t)
	dqName := "test_disk_queue_empty" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	msg := bytes.Repeat([]byte{0}, 10)
	dq := newDiskQueue(dqName, tmpDir, 100, 0, 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), int64(0))

	for i := 0; i < 100; i++ {
		err := dq.Put(msg)
		equal(t, err, nil)
		equal(t, dq.Depth(), int64(i+1))
	}

	for i := 0; i < 3; i++ {
		<-dq.ReadChan()
	}

	for {
		if dq.Depth() == 97 {
			break
		}
		time.Sleep(50 * time.Millisecond)
	}
	equal(t, dq.Depth(), int64(97))

	numFiles := dq.(*diskQueue).writeFileNum
	dq.Empty()

	assertFileNotExist(t, dq.(*diskQueue).metaDataFileName())
	for i := int64(0); i <= numFiles; i++ {
		assertFileNotExist(t, dq.(*diskQueue).fileName(i))
	}
	equal(t, dq.Depth(), int64(0))
	equal(t, dq.(*diskQueue).readFileNum, dq.(*diskQueue).writeFileNum)
	equal(t, dq.(*diskQueue).readPos, dq.(*diskQueue).writePos)
	equal(t, dq.(*diskQueue).nextReadPos, dq.(*diskQueue).readPos)
	equal(t, dq.(*diskQueue).nextReadFileNum, dq.(*diskQueue).readFileNum)

	for i := 0; i < 100; i++ {
		err := dq.Put(msg)
		equal(t, err, nil)
		equal(t, dq.Depth(), int64(i+1))
	}

	for i := 0; i < 100; i++ {
		<-dq.ReadChan()
	}

	for {
		if dq.Depth() == 0 {
			break
		}
		time.Sleep(50 * time.Millisecond)
	}

	equal(t, dq.Depth(), int64(0))
	equal(t, dq.(*diskQueue).readFileNum, dq.(*diskQueue).writeFileNum)
	equal(t, dq.(*diskQueue).readPos, dq.(*diskQueue).writePos)
	equal(t, dq.(*diskQueue).nextReadPos, dq.(*diskQueue).readPos)
}

func TestDiskQueueCorruption(t *testing.T) {
	l := newTestLogger(t)
	dqName := "test_disk_queue_corruption" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	// require a non-zero message length for the corrupt (len 0) test below
	dq := newDiskQueue(dqName, tmpDir, 1000, 10, 1<<10, 5, 2*time.Second, l)

	msg := make([]byte, 123) // 127 bytes per message, 8 (1016 bytes) messages per file
	for i := 0; i < 25; i++ {
		dq.Put(msg)
	}

	equal(t, dq.Depth(), int64(25))

	// corrupt the 2nd file
	dqFn := dq.(*diskQueue).fileName(1)
	os.Truncate(dqFn, 500) // 3 valid messages, 5 corrupted

	for i := 0; i < 19; i++ { // 1 message leftover in 4th file
		equal(t, <-dq.ReadChan(), msg)
	}

	// corrupt the 4th (current) file
	dqFn = dq.(*diskQueue).fileName(3)
	os.Truncate(dqFn, 100)

	dq.Put(msg) // in 5th file

	equal(t, <-dq.ReadChan(), msg)

	// write a corrupt (len 0) message at the 5th (current) file
	dq.(*diskQueue).writeFile.Write([]byte{0, 0, 0, 0})

	// force a new 6th file - put into 5th, then readOne errors, then put into 6th
	dq.Put(msg)
	dq.Put(msg)

	equal(t, <-dq.ReadChan(), msg)
}

func TestDiskQueueTorture(t *testing.T) {
	var wg sync.WaitGroup

	l := newTestLogger(t)
	dqName := "test_disk_queue_torture" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	dq := newDiskQueue(dqName, tmpDir, 262144, 0, 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), int64(0))

	msg := []byte("aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffffffffff")

	numWriters := 4
	numReaders := 4
	readExitChan := make(chan int)
	writeExitChan := make(chan int)

	var depth int64
	for i := 0; i < numWriters; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for {
				time.Sleep(100000 * time.Nanosecond)
				select {
				case <-writeExitChan:
					return
				default:
					err := dq.Put(msg)
					if err == nil {
						atomic.AddInt64(&depth, 1)
					}
				}
			}
		}()
	}

	time.Sleep(1 * time.Second)

	dq.Close()

	t.Logf("closing writeExitChan")
	close(writeExitChan)
	wg.Wait()

	t.Logf("restarting diskqueue")

	dq = newDiskQueue(dqName, tmpDir, 262144, 0, 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), depth)

	var read int64
	for i := 0; i < numReaders; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for {
				time.Sleep(100000 * time.Nanosecond)
				select {
				case m := <-dq.ReadChan():
					equal(t, msg, m)
					atomic.AddInt64(&read, 1)
				case <-readExitChan:
					return
				}
			}
		}()
	}

	t.Logf("waiting for depth 0")
	for {
		if dq.Depth() == 0 {
			break
		}
		time.Sleep(50 * time.Millisecond)
	}

	t.Logf("closing readExitChan")
	close(readExitChan)
	wg.Wait()

	equal(t, read, depth)

	dq.Close()
}

func BenchmarkDiskQueuePut(b *testing.B) {
	b.StopTimer()
	l := newTestLogger(b)
	dqName := "bench_disk_queue_put" + strconv.Itoa(b.N) + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	dq := newDiskQueue(dqName, tmpDir, 1024768*100, 0, 1<<10, 2500, 2*time.Second, l)
	size := 1024
	b.SetBytes(int64(size))
	data := make([]byte, size)
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		dq.Put(data)
	}
}

func BenchmarkDiskWrite(b *testing.B) {
	b.StopTimer()
	fileName := "bench_disk_queue_put" + strconv.Itoa(b.N) + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	f, _ := os.OpenFile(path.Join(tmpDir, fileName), os.O_RDWR|os.O_CREATE, 0600)
	size := 256
	b.SetBytes(int64(size))
	data := make([]byte, size)
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		f.Write(data)
	}
	f.Sync()
}

func BenchmarkDiskWriteBuffered(b *testing.B) {
	b.StopTimer()
	fileName := "bench_disk_queue_put" + strconv.Itoa(b.N) + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	f, _ := os.OpenFile(path.Join(tmpDir, fileName), os.O_RDWR|os.O_CREATE, 0600)
	size := 256
	b.SetBytes(int64(size))
	data := make([]byte, size)
	w := bufio.NewWriterSize(f, 1024*4)
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		w.Write(data)
		if i%1024 == 0 {
			w.Flush()
		}
	}
	w.Flush()
	f.Sync()
}

// this benchmark should be run via:
//    $ go test -test.bench 'DiskQueueGet' -test.benchtime 0.1
// (so that it does not perform too many iterations)
func BenchmarkDiskQueueGet(b *testing.B) {
	b.StopTimer()
	l := newTestLogger(b)
	dqName := "bench_disk_queue_get" + strconv.Itoa(b.N) + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	dq := newDiskQueue(dqName, tmpDir, 1024768, 0, 1<<10, 2500, 2*time.Second, l)
	data := []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaa")
	b.SetBytes(int64(len(data)))
	for i := 0; i < b.N; i++ {
		dq.Put(data)
	}
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		<-dq.ReadChan()
	}
}
<commit_msg>update invocation syntax<commit_after>package nsqd

import (
	"bufio"
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strconv"
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

func TestDiskQueue(t *testing.T) {
	l := newTestLogger(t)

	dqName := "test_disk_queue" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	dq := newDiskQueue(dqName, tmpDir, 1024, 4, 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), int64(0))

	msg := []byte("test")
	err = dq.Put(msg)
	equal(t, err, nil)
	equal(t, dq.Depth(), int64(1))

	msgOut := <-dq.ReadChan()
	equal(t, msgOut, msg)
}

func TestDiskQueueRoll(t *testing.T) {
	l := newTestLogger(t)
	dqName := "test_disk_queue_roll" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	msg := bytes.Repeat([]byte{0}, 10)
	ml := int64(len(msg))
	dq := newDiskQueue(dqName, tmpDir, 9*(ml+4), int32(ml), 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), int64(0))

	for i := 0; i < 10; i++ {
		err := dq.Put(msg)
		equal(t, err, nil)
		equal(t, dq.Depth(), int64(i+1))
	}

	equal(t, dq.(*diskQueue).writeFileNum, int64(1))
	equal(t, dq.(*diskQueue).writePos, int64(0))
}

func assertFileNotExist(t *testing.T, fn string) {
	f, err := os.OpenFile(fn, os.O_RDONLY, 0600)
	equal(t, f, (*os.File)(nil))
	equal(t, os.IsNotExist(err), true)
}

func TestDiskQueueEmpty(t *testing.T) {
	l := newTestLogger(t)
	dqName := "test_disk_queue_empty" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	msg := bytes.Repeat([]byte{0}, 10)
	dq := newDiskQueue(dqName, tmpDir, 100, 0, 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), int64(0))

	for i := 0; i < 100; i++ {
		err := dq.Put(msg)
		equal(t, err, nil)
		equal(t, dq.Depth(), int64(i+1))
	}

	for i := 0; i < 3; i++ {
		<-dq.ReadChan()
	}

	for {
		if dq.Depth() == 97 {
			break
		}
		time.Sleep(50 * time.Millisecond)
	}
	equal(t, dq.Depth(), int64(97))

	numFiles := dq.(*diskQueue).writeFileNum
	dq.Empty()

	assertFileNotExist(t, dq.(*diskQueue).metaDataFileName())
	for i := int64(0); i <= numFiles; i++ {
		assertFileNotExist(t, dq.(*diskQueue).fileName(i))
	}
	equal(t, dq.Depth(), int64(0))
	equal(t, dq.(*diskQueue).readFileNum, dq.(*diskQueue).writeFileNum)
	equal(t, dq.(*diskQueue).readPos, dq.(*diskQueue).writePos)
	equal(t, dq.(*diskQueue).nextReadPos, dq.(*diskQueue).readPos)
	equal(t, dq.(*diskQueue).nextReadFileNum, dq.(*diskQueue).readFileNum)

	for i := 0; i < 100; i++ {
		err := dq.Put(msg)
		equal(t, err, nil)
		equal(t, dq.Depth(), int64(i+1))
	}

	for i := 0; i < 100; i++ {
		<-dq.ReadChan()
	}

	for {
		if dq.Depth() == 0 {
			break
		}
		time.Sleep(50 * time.Millisecond)
	}

	equal(t, dq.Depth(), int64(0))
	equal(t, dq.(*diskQueue).readFileNum, dq.(*diskQueue).writeFileNum)
	equal(t, dq.(*diskQueue).readPos, dq.(*diskQueue).writePos)
	equal(t, dq.(*diskQueue).nextReadPos, dq.(*diskQueue).readPos)
}

func TestDiskQueueCorruption(t *testing.T) {
	l := newTestLogger(t)
	dqName := "test_disk_queue_corruption" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	// require a non-zero message length for the corrupt (len 0) test below
	dq := newDiskQueue(dqName, tmpDir, 1000, 10, 1<<10, 5, 2*time.Second, l)

	msg := make([]byte, 123) // 127 bytes per message, 8 (1016 bytes) messages per file
	for i := 0; i < 25; i++ {
		dq.Put(msg)
	}

	equal(t, dq.Depth(), int64(25))

	// corrupt the 2nd file
	dqFn := dq.(*diskQueue).fileName(1)
	os.Truncate(dqFn, 500) // 3 valid messages, 5 corrupted

	for i := 0; i < 19; i++ { // 1 message leftover in 4th file
		equal(t, <-dq.ReadChan(), msg)
	}

	// corrupt the 4th (current) file
	dqFn = dq.(*diskQueue).fileName(3)
	os.Truncate(dqFn, 100)

	dq.Put(msg) // in 5th file

	equal(t, <-dq.ReadChan(), msg)

	// write a corrupt (len 0) message at the 5th (current) file
	dq.(*diskQueue).writeFile.Write([]byte{0, 0, 0, 0})

	// force a new 6th file - put into 5th, then readOne errors, then put into 6th
	dq.Put(msg)
	dq.Put(msg)

	equal(t, <-dq.ReadChan(), msg)
}

func TestDiskQueueTorture(t *testing.T) {
	var wg sync.WaitGroup

	l := newTestLogger(t)
	dqName := "test_disk_queue_torture" + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	dq := newDiskQueue(dqName, tmpDir, 262144, 0, 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), int64(0))

	msg := []byte("aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffffffffff")

	numWriters := 4
	numReaders := 4
	readExitChan := make(chan int)
	writeExitChan := make(chan int)

	var depth int64
	for i := 0; i < numWriters; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for {
				time.Sleep(100000 * time.Nanosecond)
				select {
				case <-writeExitChan:
					return
				default:
					err := dq.Put(msg)
					if err == nil {
						atomic.AddInt64(&depth, 1)
					}
				}
			}
		}()
	}

	time.Sleep(1 * time.Second)

	dq.Close()

	t.Logf("closing writeExitChan")
	close(writeExitChan)
	wg.Wait()

	t.Logf("restarting diskqueue")

	dq = newDiskQueue(dqName, tmpDir, 262144, 0, 1<<10, 2500, 2*time.Second, l)
	nequal(t, dq, nil)
	equal(t, dq.Depth(), depth)

	var read int64
	for i := 0; i < numReaders; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for {
				time.Sleep(100000 * time.Nanosecond)
				select {
				case m := <-dq.ReadChan():
					equal(t, msg, m)
					atomic.AddInt64(&read, 1)
				case <-readExitChan:
					return
				}
			}
		}()
	}

	t.Logf("waiting for depth 0")
	for {
		if dq.Depth() == 0 {
			break
		}
		time.Sleep(50 * time.Millisecond)
	}

	t.Logf("closing readExitChan")
	close(readExitChan)
	wg.Wait()

	equal(t, read, depth)

	dq.Close()
}

func BenchmarkDiskQueuePut(b *testing.B) {
	b.StopTimer()
	l := newTestLogger(b)
	dqName := "bench_disk_queue_put" + strconv.Itoa(b.N) + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	dq := newDiskQueue(dqName, tmpDir, 1024768*100, 0, 1<<10, 2500, 2*time.Second, l)
	size := 1024
	b.SetBytes(int64(size))
	data := make([]byte, size)
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		dq.Put(data)
	}
}

func BenchmarkDiskWrite(b *testing.B) {
	b.StopTimer()
	fileName := "bench_disk_queue_put" + strconv.Itoa(b.N) + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	f, _ := os.OpenFile(path.Join(tmpDir, fileName), os.O_RDWR|os.O_CREATE, 0600)
	size := 256
	b.SetBytes(int64(size))
	data := make([]byte, size)
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		f.Write(data)
	}
	f.Sync()
}

func BenchmarkDiskWriteBuffered(b *testing.B) {
	b.StopTimer()
	fileName := "bench_disk_queue_put" + strconv.Itoa(b.N) + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	f, _ := os.OpenFile(path.Join(tmpDir, fileName), os.O_RDWR|os.O_CREATE, 0600)
	size := 256
	b.SetBytes(int64(size))
	data := make([]byte, size)
	w := bufio.NewWriterSize(f, 1024*4)
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		w.Write(data)
		if i%1024 == 0 {
			w.Flush()
		}
	}
	w.Flush()
	f.Sync()
}

// you might want to run this like
// $ go test -bench=DiskQueueGet -benchtime 0.1s
// too avoid doing too many iterations.
func BenchmarkDiskQueueGet(b *testing.B) {
	b.StopTimer()
	l := newTestLogger(b)
	dqName := "bench_disk_queue_get" + strconv.Itoa(b.N) + strconv.Itoa(int(time.Now().Unix()))
	tmpDir, err := ioutil.TempDir("", fmt.Sprintf("nsq-test-%d", time.Now().UnixNano()))
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)
	dq := newDiskQueue(dqName, tmpDir, 1024768, 0, 1<<10, 2500, 2*time.Second, l)
	data := []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaa")
	b.SetBytes(int64(len(data)))
	for i := 0; i < b.N; i++ {
		dq.Put(data)
	}
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		<-dq.ReadChan()
	}
}
<|endoftext|>


<commit_before>/*
http://www.apache.org/licenses/LICENSE-2.0.txt

Copyright 2015 Intel Corporation

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 scheduler

import (
	"errors"
	"fmt"
	"net"
	"strconv"
	"sync"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/intelsdi-x/gomit"
	"github.com/pborman/uuid"

	"github.com/intelsdi-x/snap/core"
	"github.com/intelsdi-x/snap/core/scheduler_event"
	"github.com/intelsdi-x/snap/grpc/controlproxy"
	"github.com/intelsdi-x/snap/pkg/schedule"
	"github.com/intelsdi-x/snap/scheduler/wmap"
)

const (
	// DefaultDeadlineDuration - The default timeout is 5 second
	DefaultDeadlineDuration = time.Second * 5
	// DefaultStopOnFailure - The default stopping a failure is after three tries
	DefaultStopOnFailure = 3
)

var (
	taskLogger = schedulerLogger.WithField("_module", "scheduler-task")

	// ErrTaskNotFound - The error message for task not found
	ErrTaskNotFound = errors.New("Task not found")
	// ErrTaskNotStopped - The error message for task must be stopped
	ErrTaskNotStopped = errors.New("Task must be stopped")
	// ErrTaskHasAlreadyBeenAdded - The error message for task has already been added
	ErrTaskHasAlreadyBeenAdded = errors.New("Task has already been added")
	// ErrTaskDisabledOnFailures - The error message for task disabled due to consecutive failures
	ErrTaskDisabledOnFailures = errors.New("Task disabled due to consecutive failures")
	// ErrTaskNotDisabled - The error message for task must be disabled
	ErrTaskNotDisabled = errors.New("Task must be disabled")
)

type task struct {
	sync.Mutex //protects state

	id                 string
	name               string
	schResponseChan    chan schedule.Response
	killChan           chan struct{}
	schedule           schedule.Schedule
	workflow           *schedulerWorkflow
	state              core.TaskState
	creationTime       time.Time
	lastFireTime       time.Time
	manager            managesWork
	metricsManager     managesMetrics
	deadlineDuration   time.Duration
	hitCount           uint
	missedIntervals    uint
	failureMutex       sync.Mutex
	failedRuns         uint
	lastFailureMessage string
	lastFailureTime    time.Time
	stopOnFailure      int
	eventEmitter       gomit.Emitter
	RemoteManagers     managers
}

//NewTask creates a Task
func newTask(s schedule.Schedule, wf *schedulerWorkflow, m *workManager, mm managesMetrics, emitter gomit.Emitter, opts ...core.TaskOption) (*task, error) {

	//Task would always be given a default name.
	//However if a user want to change this name, she can pass optional arguments, in form of core.TaskOption
	//The new name then get over written.

	taskID := uuid.New()
	name := fmt.Sprintf("Task-%s", taskID)
	wf.eventEmitter = emitter
	mgrs := newManagers(mm)
	err := createTaskClients(&mgrs, wf)
	if err != nil {
		return nil, err
	}
	task := &task{
		id:               taskID,
		name:             name,
		schResponseChan:  make(chan schedule.Response),
		schedule:         s,
		state:            core.TaskStopped,
		creationTime:     time.Now(),
		workflow:         wf,
		manager:          m,
		metricsManager:   mm,
		deadlineDuration: DefaultDeadlineDuration,
		stopOnFailure:    DefaultStopOnFailure,
		eventEmitter:     emitter,
		RemoteManagers:   mgrs,
	}
	//set options
	for _, opt := range opts {
		opt(task)
	}
	return task, nil
}

// Option sets the options specified.
// Returns an option to optionally restore the last arg's previous value.
func (t *task) Option(opts ...core.TaskOption) core.TaskOption {
	var previous core.TaskOption
	for _, opt := range opts {
		previous = opt(t)
	}
	return previous
}

//Returns the name of the task
func (t *task) GetName() string {
	return t.name
}

func (t *task) SetName(name string) {
	t.name = name
}

// CreateTime returns the time the task was created.
func (t *task) CreationTime() *time.Time {
	return &t.creationTime
}

func (t *task) DeadlineDuration() time.Duration {
	return t.deadlineDuration
}

func (t *task) SetDeadlineDuration(d time.Duration) {
	t.deadlineDuration = d
}

func (t *task) SetTaskID(id string) {
	t.id = id
}

// HitCount returns the number of times the task has fired.
func (t *task) HitCount() uint {
	return t.hitCount
}

// Id returns the tasks Id.
func (t *task) ID() string {
	return t.id
}

// LastRunTime returns the time of the tasks last run.
func (t *task) LastRunTime() *time.Time {
	return &t.lastFireTime
}

// MissedCount returns the number of intervals missed.
func (t *task) MissedCount() uint {
	return t.missedIntervals
}

// FailedRuns returns the number of intervals missed.
func (t *task) FailedCount() uint {
	return t.failedRuns
}

// LastFailureMessage returns the last error from a task run
func (t *task) LastFailureMessage() string {
	return t.lastFailureMessage
}

// State returns state of the task.
func (t *task) State() core.TaskState {
	return t.state
}

// Status returns the state of the workflow.
func (t *task) Status() WorkflowState {
	return t.workflow.State()
}

func (t *task) SetStopOnFailure(v int) {
	t.stopOnFailure = v
}

func (t *task) SetID(id string) {
	t.id = id
}

func (t *task) GetStopOnFailure() int {
	return t.stopOnFailure
}

// Spin will start a task spinning in its own routine while it waits for its
// schedule.
func (t *task) Spin() {
	// We need to lock long enough to change state
	t.Lock()
	defer t.Unlock()
	// Reset the lastFireTime at each Spin.
	// This ensures misses are tracked only forward of the point
	// in time that a task starts spinning. E.g. stopping a task,
	// waiting a period of time, and starting the task won't show
	// misses for the interval while stopped.
	t.lastFireTime = time.Now()
	if t.state == core.TaskStopped {
		t.state = core.TaskSpinning
		t.killChan = make(chan struct{})
		// spin in a goroutine
		go t.spin()
	}
}

func (t *task) Stop() {
	t.Lock()
	defer t.Unlock()
	if t.state == core.TaskFiring || t.state == core.TaskSpinning {
		t.state = core.TaskStopping
		close(t.killChan)
	}
}

//Enable changes the state from Disabled to Stopped
func (t *task) Enable() error {
	t.Lock()
	defer t.Unlock()

	if t.state != core.TaskDisabled {
		return ErrTaskNotDisabled
	}
	t.state = core.TaskStopped

	return nil
}

func (t *task) Kill() {
	t.Lock()
	defer t.Unlock()
	if t.state == core.TaskFiring || t.state == core.TaskSpinning {
		close(t.killChan)
		t.state = core.TaskDisabled
	}
}

func (t *task) WMap() *wmap.WorkflowMap {
	return t.workflow.workflowMap
}

func (t *task) Schedule() schedule.Schedule {
	return t.schedule
}

func (t *task) spin() {
	var consecutiveFailures int
	for {
		taskLogger.Debug("task spin loop")
		// Start go routine to wait on schedule
		go t.waitForSchedule()
		// wait here on
		//  schResponseChan - response from schedule
		//  killChan - signals task needs to be stopped
		select {
		case sr := <-t.schResponseChan:
			switch sr.State() {
			// If response show this schedule is stil active we fire
			case schedule.Active:
				t.missedIntervals += sr.Missed()
				t.lastFireTime = time.Now()
				t.hitCount++
				t.fire()
				if t.lastFailureTime == t.lastFireTime {
					consecutiveFailures++
					taskLogger.WithFields(log.Fields{
						"_block":                    "spin",
						"task-id":                   t.id,
						"task-name":                 t.name,
						"consecutive failures":      consecutiveFailures,
						"consecutive failure limit": t.stopOnFailure,
						"error":                     t.lastFailureMessage,
					}).Warn("Task failed")
				} else {
					consecutiveFailures = 0
				}
				if t.stopOnFailure >= 0 && consecutiveFailures >= t.stopOnFailure {
					taskLogger.WithFields(log.Fields{
						"_block":               "spin",
						"task-id":              t.id,
						"task-name":            t.name,
						"consecutive failures": consecutiveFailures,
						"error":                t.lastFailureMessage,
					}).Error(ErrTaskDisabledOnFailures)
					// You must lock on state change for tasks
					t.Lock()
					t.state = core.TaskDisabled
					t.Unlock()
					// Send task disabled event
					event := new(scheduler_event.TaskDisabledEvent)
					event.TaskID = t.id
					event.Why = fmt.Sprintf("Task disabled with error: %s", t.lastFailureMessage)
					defer t.eventEmitter.Emit(event)
					return
				}

			// Schedule has ended
			case schedule.Ended:
				// You must lock task to change state
				t.Lock()
				t.state = core.TaskEnded
				t.Unlock()
				return //spin

			// Schedule has errored
			case schedule.Error:
				// You must lock task to change state
				t.Lock()
				t.state = core.TaskDisabled
				t.Unlock()
				return //spin

			}
		case <-t.killChan:
			// Only here can it truly be stopped
			t.Lock()
			t.state = core.TaskStopped
			t.lastFireTime = time.Time{}
			t.Unlock()
			return
		}
	}
}

func (t *task) fire() {
	t.Lock()
	defer t.Unlock()

	t.state = core.TaskFiring
	t.workflow.Start(t)
	t.state = core.TaskSpinning
}

func (t *task) waitForSchedule() {
	select {
	case <-t.killChan:
		return
	case t.schResponseChan <- t.schedule.Wait(t.lastFireTime):
	}
}

// RecordFailure updates the failed runs and last failure properties
func (t *task) RecordFailure(e []error) {
	// We synchronize this update to ensure it is atomic
	t.failureMutex.Lock()
	defer t.failureMutex.Unlock()
	t.failedRuns++
	t.lastFailureTime = t.lastFireTime
	t.lastFailureMessage = e[len(e)-1].Error()
}

type taskCollection struct {
	*sync.Mutex

	table map[string]*task
}

func newTaskCollection() *taskCollection {
	return &taskCollection{
		Mutex: &sync.Mutex{},

		table: make(map[string]*task),
	}
}

// Get given a task id returns a Task or nil if not found
func (t *taskCollection) Get(id string) *task {
	t.Lock()
	defer t.Unlock()

	if t, ok := t.table[id]; ok {
		return t
	}
	return nil
}

// Add given a reference to a task adds it to the collection of tasks.  An
// error is returned if the task already exists in the collection.
func (t *taskCollection) add(task *task) error {
	t.Lock()
	defer t.Unlock()

	if _, ok := t.table[task.id]; !ok {
		//If we don't already have this task in the collection save it
		t.table[task.id] = task
	} else {
		taskLogger.WithFields(log.Fields{
			"_module": "scheduler-taskCollection",
			"_block":  "add",
			"task id": task.id,
		}).Error(ErrTaskHasAlreadyBeenAdded.Error())
		return ErrTaskHasAlreadyBeenAdded
	}

	return nil
}

// remove will remove a given task from tasks.  The task must be stopped.
// Can return errors ErrTaskNotFound and ErrTaskNotStopped.
func (t *taskCollection) remove(task *task) error {
	t.Lock()
	defer t.Unlock()
	if _, ok := t.table[task.id]; ok {
		if task.state != core.TaskStopped {
			taskLogger.WithFields(log.Fields{
				"_block":  "remove",
				"task id": task.id,
			}).Error(ErrTaskNotStopped)
			return ErrTaskNotStopped
		}
		delete(t.table, task.id)
	} else {
		taskLogger.WithFields(log.Fields{
			"_block":  "remove",
			"task id": task.id,
		}).Error(ErrTaskNotFound)
		return ErrTaskNotFound
	}
	return nil
}

// Table returns a copy of the taskCollection
func (t *taskCollection) Table() map[string]*task {
	t.Lock()
	defer t.Unlock()
	tasks := make(map[string]*task)
	for id, t := range t.table {
		tasks[id] = t
	}
	return tasks
}

// createTaskClients walks the workflowmap and creates clients for this task
// remoteManagers so that nodes that require proxy request can make them.
func createTaskClients(mgrs *managers, wf *schedulerWorkflow) error {
	return walkWorkflow(wf.processNodes, wf.publishNodes, mgrs)
}

func walkWorkflow(prnodes []*processNode, pbnodes []*publishNode, mgrs *managers) error {
	for _, pr := range prnodes {
		if pr.Target != "" {
			host, port, err := net.SplitHostPort(pr.Target)
			if err != nil {
				return err
			}
			p, err := strconv.Atoi(port)
			if err != nil {
				return err
			}
			proxy, err := controlproxy.New(host, p)
			if err != nil {
				return err
			}
			mgrs.Add(pr.Target, proxy)
		}
		err := walkWorkflow(pr.ProcessNodes, pr.PublishNodes, mgrs)
		if err != nil {
			return err
		}

	}
	for _, pu := range pbnodes {
		if pu.Target != "" {
			host, port, err := net.SplitHostPort(pu.Target)
			if err != nil {
				return err
			}
			p, err := strconv.Atoi(port)
			if err != nil {
				return err
			}
			proxy, err := controlproxy.New(host, p)
			if err != nil {
				return err
			}
			mgrs.Add(pu.Target, proxy)
		}
	}
	return nil
}
<commit_msg>Fixes 1043: Modifies snap to allow for removal of disabled tasks<commit_after>/*
http://www.apache.org/licenses/LICENSE-2.0.txt

Copyright 2015 Intel Corporation

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 scheduler

import (
	"errors"
	"fmt"
	"net"
	"strconv"
	"sync"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/intelsdi-x/gomit"
	"github.com/pborman/uuid"

	"github.com/intelsdi-x/snap/core"
	"github.com/intelsdi-x/snap/core/scheduler_event"
	"github.com/intelsdi-x/snap/grpc/controlproxy"
	"github.com/intelsdi-x/snap/pkg/schedule"
	"github.com/intelsdi-x/snap/scheduler/wmap"
)

const (
	// DefaultDeadlineDuration - The default timeout is 5 second
	DefaultDeadlineDuration = time.Second * 5
	// DefaultStopOnFailure - The default stopping a failure is after three tries
	DefaultStopOnFailure = 3
)

var (
	taskLogger = schedulerLogger.WithField("_module", "scheduler-task")

	// ErrTaskNotFound - The error message for task not found
	ErrTaskNotFound = errors.New("Task not found")
	// ErrTaskNotStopped - The error message for task must be stopped
	ErrTaskNotStopped = errors.New("Task must be stopped")
	// ErrTaskHasAlreadyBeenAdded - The error message for task has already been added
	ErrTaskHasAlreadyBeenAdded = errors.New("Task has already been added")
	// ErrTaskDisabledOnFailures - The error message for task disabled due to consecutive failures
	ErrTaskDisabledOnFailures = errors.New("Task disabled due to consecutive failures")
	// ErrTaskNotDisabled - The error message for task must be disabled
	ErrTaskNotDisabled = errors.New("Task must be disabled")
)

type task struct {
	sync.Mutex //protects state

	id                 string
	name               string
	schResponseChan    chan schedule.Response
	killChan           chan struct{}
	schedule           schedule.Schedule
	workflow           *schedulerWorkflow
	state              core.TaskState
	creationTime       time.Time
	lastFireTime       time.Time
	manager            managesWork
	metricsManager     managesMetrics
	deadlineDuration   time.Duration
	hitCount           uint
	missedIntervals    uint
	failureMutex       sync.Mutex
	failedRuns         uint
	lastFailureMessage string
	lastFailureTime    time.Time
	stopOnFailure      int
	eventEmitter       gomit.Emitter
	RemoteManagers     managers
}

//NewTask creates a Task
func newTask(s schedule.Schedule, wf *schedulerWorkflow, m *workManager, mm managesMetrics, emitter gomit.Emitter, opts ...core.TaskOption) (*task, error) {

	//Task would always be given a default name.
	//However if a user want to change this name, she can pass optional arguments, in form of core.TaskOption
	//The new name then get over written.

	taskID := uuid.New()
	name := fmt.Sprintf("Task-%s", taskID)
	wf.eventEmitter = emitter
	mgrs := newManagers(mm)
	err := createTaskClients(&mgrs, wf)
	if err != nil {
		return nil, err
	}
	task := &task{
		id:               taskID,
		name:             name,
		schResponseChan:  make(chan schedule.Response),
		schedule:         s,
		state:            core.TaskStopped,
		creationTime:     time.Now(),
		workflow:         wf,
		manager:          m,
		metricsManager:   mm,
		deadlineDuration: DefaultDeadlineDuration,
		stopOnFailure:    DefaultStopOnFailure,
		eventEmitter:     emitter,
		RemoteManagers:   mgrs,
	}
	//set options
	for _, opt := range opts {
		opt(task)
	}
	return task, nil
}

// Option sets the options specified.
// Returns an option to optionally restore the last arg's previous value.
func (t *task) Option(opts ...core.TaskOption) core.TaskOption {
	var previous core.TaskOption
	for _, opt := range opts {
		previous = opt(t)
	}
	return previous
}

//Returns the name of the task
func (t *task) GetName() string {
	return t.name
}

func (t *task) SetName(name string) {
	t.name = name
}

// CreateTime returns the time the task was created.
func (t *task) CreationTime() *time.Time {
	return &t.creationTime
}

func (t *task) DeadlineDuration() time.Duration {
	return t.deadlineDuration
}

func (t *task) SetDeadlineDuration(d time.Duration) {
	t.deadlineDuration = d
}

func (t *task) SetTaskID(id string) {
	t.id = id
}

// HitCount returns the number of times the task has fired.
func (t *task) HitCount() uint {
	return t.hitCount
}

// Id returns the tasks Id.
func (t *task) ID() string {
	return t.id
}

// LastRunTime returns the time of the tasks last run.
func (t *task) LastRunTime() *time.Time {
	return &t.lastFireTime
}

// MissedCount returns the number of intervals missed.
func (t *task) MissedCount() uint {
	return t.missedIntervals
}

// FailedRuns returns the number of intervals missed.
func (t *task) FailedCount() uint {
	return t.failedRuns
}

// LastFailureMessage returns the last error from a task run
func (t *task) LastFailureMessage() string {
	return t.lastFailureMessage
}

// State returns state of the task.
func (t *task) State() core.TaskState {
	return t.state
}

// Status returns the state of the workflow.
func (t *task) Status() WorkflowState {
	return t.workflow.State()
}

func (t *task) SetStopOnFailure(v int) {
	t.stopOnFailure = v
}

func (t *task) SetID(id string) {
	t.id = id
}

func (t *task) GetStopOnFailure() int {
	return t.stopOnFailure
}

// Spin will start a task spinning in its own routine while it waits for its
// schedule.
func (t *task) Spin() {
	// We need to lock long enough to change state
	t.Lock()
	defer t.Unlock()
	// Reset the lastFireTime at each Spin.
	// This ensures misses are tracked only forward of the point
	// in time that a task starts spinning. E.g. stopping a task,
	// waiting a period of time, and starting the task won't show
	// misses for the interval while stopped.
	t.lastFireTime = time.Now()
	if t.state == core.TaskStopped {
		t.state = core.TaskSpinning
		t.killChan = make(chan struct{})
		// spin in a goroutine
		go t.spin()
	}
}

func (t *task) Stop() {
	t.Lock()
	defer t.Unlock()
	if t.state == core.TaskFiring || t.state == core.TaskSpinning {
		t.state = core.TaskStopping
		close(t.killChan)
	}
}

//Enable changes the state from Disabled to Stopped
func (t *task) Enable() error {
	t.Lock()
	defer t.Unlock()

	if t.state != core.TaskDisabled {
		return ErrTaskNotDisabled
	}
	t.state = core.TaskStopped

	return nil
}

func (t *task) Kill() {
	t.Lock()
	defer t.Unlock()
	if t.state == core.TaskFiring || t.state == core.TaskSpinning {
		close(t.killChan)
		t.state = core.TaskDisabled
	}
}

func (t *task) WMap() *wmap.WorkflowMap {
	return t.workflow.workflowMap
}

func (t *task) Schedule() schedule.Schedule {
	return t.schedule
}

func (t *task) spin() {
	var consecutiveFailures int
	for {
		taskLogger.Debug("task spin loop")
		// Start go routine to wait on schedule
		go t.waitForSchedule()
		// wait here on
		//  schResponseChan - response from schedule
		//  killChan - signals task needs to be stopped
		select {
		case sr := <-t.schResponseChan:
			switch sr.State() {
			// If response show this schedule is stil active we fire
			case schedule.Active:
				t.missedIntervals += sr.Missed()
				t.lastFireTime = time.Now()
				t.hitCount++
				t.fire()
				if t.lastFailureTime == t.lastFireTime {
					consecutiveFailures++
					taskLogger.WithFields(log.Fields{
						"_block":                    "spin",
						"task-id":                   t.id,
						"task-name":                 t.name,
						"consecutive failures":      consecutiveFailures,
						"consecutive failure limit": t.stopOnFailure,
						"error":                     t.lastFailureMessage,
					}).Warn("Task failed")
				} else {
					consecutiveFailures = 0
				}
				if t.stopOnFailure >= 0 && consecutiveFailures >= t.stopOnFailure {
					taskLogger.WithFields(log.Fields{
						"_block":               "spin",
						"task-id":              t.id,
						"task-name":            t.name,
						"consecutive failures": consecutiveFailures,
						"error":                t.lastFailureMessage,
					}).Error(ErrTaskDisabledOnFailures)
					// You must lock on state change for tasks
					t.Lock()
					t.state = core.TaskDisabled
					t.Unlock()
					// Send task disabled event
					event := new(scheduler_event.TaskDisabledEvent)
					event.TaskID = t.id
					event.Why = fmt.Sprintf("Task disabled with error: %s", t.lastFailureMessage)
					defer t.eventEmitter.Emit(event)
					return
				}

			// Schedule has ended
			case schedule.Ended:
				// You must lock task to change state
				t.Lock()
				t.state = core.TaskEnded
				t.Unlock()
				return //spin

			// Schedule has errored
			case schedule.Error:
				// You must lock task to change state
				t.Lock()
				t.state = core.TaskDisabled
				t.Unlock()
				return //spin

			}
		case <-t.killChan:
			// Only here can it truly be stopped
			t.Lock()
			t.state = core.TaskStopped
			t.lastFireTime = time.Time{}
			t.Unlock()
			return
		}
	}
}

func (t *task) fire() {
	t.Lock()
	defer t.Unlock()

	t.state = core.TaskFiring
	t.workflow.Start(t)
	t.state = core.TaskSpinning
}

func (t *task) waitForSchedule() {
	select {
	case <-t.killChan:
		return
	case t.schResponseChan <- t.schedule.Wait(t.lastFireTime):
	}
}

// RecordFailure updates the failed runs and last failure properties
func (t *task) RecordFailure(e []error) {
	// We synchronize this update to ensure it is atomic
	t.failureMutex.Lock()
	defer t.failureMutex.Unlock()
	t.failedRuns++
	t.lastFailureTime = t.lastFireTime
	t.lastFailureMessage = e[len(e)-1].Error()
}

type taskCollection struct {
	*sync.Mutex

	table map[string]*task
}

func newTaskCollection() *taskCollection {
	return &taskCollection{
		Mutex: &sync.Mutex{},

		table: make(map[string]*task),
	}
}

// Get given a task id returns a Task or nil if not found
func (t *taskCollection) Get(id string) *task {
	t.Lock()
	defer t.Unlock()

	if t, ok := t.table[id]; ok {
		return t
	}
	return nil
}

// Add given a reference to a task adds it to the collection of tasks.  An
// error is returned if the task already exists in the collection.
func (t *taskCollection) add(task *task) error {
	t.Lock()
	defer t.Unlock()

	if _, ok := t.table[task.id]; !ok {
		//If we don't already have this task in the collection save it
		t.table[task.id] = task
	} else {
		taskLogger.WithFields(log.Fields{
			"_module": "scheduler-taskCollection",
			"_block":  "add",
			"task id": task.id,
		}).Error(ErrTaskHasAlreadyBeenAdded.Error())
		return ErrTaskHasAlreadyBeenAdded
	}

	return nil
}

// remove will remove a given task from tasks.  The task must be stopped.
// Can return errors ErrTaskNotFound and ErrTaskNotStopped.
func (t *taskCollection) remove(task *task) error {
	t.Lock()
	defer t.Unlock()
	if _, ok := t.table[task.id]; ok {
		if task.state != core.TaskStopped && task.state != core.TaskDisabled {
			taskLogger.WithFields(log.Fields{
				"_block":  "remove",
				"task id": task.id,
			}).Error(ErrTaskNotStopped)
			return ErrTaskNotStopped
		}
		delete(t.table, task.id)
	} else {
		taskLogger.WithFields(log.Fields{
			"_block":  "remove",
			"task id": task.id,
		}).Error(ErrTaskNotFound)
		return ErrTaskNotFound
	}
	return nil
}

// Table returns a copy of the taskCollection
func (t *taskCollection) Table() map[string]*task {
	t.Lock()
	defer t.Unlock()
	tasks := make(map[string]*task)
	for id, t := range t.table {
		tasks[id] = t
	}
	return tasks
}

// createTaskClients walks the workflowmap and creates clients for this task
// remoteManagers so that nodes that require proxy request can make them.
func createTaskClients(mgrs *managers, wf *schedulerWorkflow) error {
	return walkWorkflow(wf.processNodes, wf.publishNodes, mgrs)
}

func walkWorkflow(prnodes []*processNode, pbnodes []*publishNode, mgrs *managers) error {
	for _, pr := range prnodes {
		if pr.Target != "" {
			host, port, err := net.SplitHostPort(pr.Target)
			if err != nil {
				return err
			}
			p, err := strconv.Atoi(port)
			if err != nil {
				return err
			}
			proxy, err := controlproxy.New(host, p)
			if err != nil {
				return err
			}
			mgrs.Add(pr.Target, proxy)
		}
		err := walkWorkflow(pr.ProcessNodes, pr.PublishNodes, mgrs)
		if err != nil {
			return err
		}

	}
	for _, pu := range pbnodes {
		if pu.Target != "" {
			host, port, err := net.SplitHostPort(pu.Target)
			if err != nil {
				return err
			}
			p, err := strconv.Atoi(port)
			if err != nil {
				return err
			}
			proxy, err := controlproxy.New(host, p)
			if err != nil {
				return err
			}
			mgrs.Add(pu.Target, proxy)
		}
	}
	return nil
}
<|endoftext|>


<commit_before>// +build kube

/*
   Copyright 2020 Docker Compose CLI authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package client

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/docker/compose-cli/pkg/api"
	"github.com/docker/compose-cli/pkg/utils"

	"golang.org/x/sync/errgroup"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/portforward"
	"k8s.io/client-go/tools/remotecommand"
	"k8s.io/client-go/transport/spdy"
)

// KubeClient API to access kube objects
type KubeClient struct {
	client    *kubernetes.Clientset
	namespace string
	config    *rest.Config
	ioStreams genericclioptions.IOStreams
}

// NewKubeClient new kubernetes client
func NewKubeClient(config genericclioptions.RESTClientGetter) (*KubeClient, error) {
	restConfig, err := config.ToRESTConfig()
	if err != nil {
		return nil, err
	}

	clientset, err := kubernetes.NewForConfig(restConfig)
	if err != nil {
		return nil, fmt.Errorf("failed creating clientset. Error: %+v", err)
	}

	namespace, _, err := config.ToRawKubeConfigLoader().Namespace()
	if err != nil {
		return nil, err
	}

	return &KubeClient{
		client:    clientset,
		namespace: namespace,
		config:    restConfig,
		ioStreams: genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr},
	}, nil
}

// GetPod retrieves a service pod
func (kc KubeClient) GetPod(ctx context.Context, projectName, serviceName string) (*corev1.Pod, error) {
	pods, err := kc.client.CoreV1().Pods(kc.namespace).List(ctx, metav1.ListOptions{
		LabelSelector: fmt.Sprintf("%s=%s", api.ProjectLabel, projectName),
	})
	if err != nil {
		return nil, err
	}
	if pods == nil {
		return nil, nil
	}
	var pod corev1.Pod
	for _, p := range pods.Items {
		service := p.Labels[api.ServiceLabel]
		if service == serviceName {
			pod = p
			break
		}
	}
	return &pod, nil
}

// Exec executes a command in a container
func (kc KubeClient) Exec(ctx context.Context, projectName string, opts api.RunOptions) error {
	pod, err := kc.GetPod(ctx, projectName, opts.Service)
	if err != nil || pod == nil {
		return err
	}
	if len(pod.Spec.Containers) == 0 {
		return fmt.Errorf("no containers running in pod %s", pod.Name)
	}
	// get first container in the pod
	container := &pod.Spec.Containers[0]
	containerName := container.Name

	req := kc.client.CoreV1().RESTClient().Post().
		Resource("pods").
		Name(pod.Name).
		Namespace(kc.namespace).
		SubResource("exec")

	option := &corev1.PodExecOptions{
		Container: containerName,
		Command:   opts.Command,
		Stdin:     true,
		Stdout:    true,
		Stderr:    true,
		TTY:       opts.Tty,
	}

	if opts.Stdin == nil {
		option.Stdin = false
	}

	scheme := runtime.NewScheme()
	if err := corev1.AddToScheme(scheme); err != nil {
		return fmt.Errorf("error adding to scheme: %v", err)
	}
	parameterCodec := runtime.NewParameterCodec(scheme)
	req.VersionedParams(option, parameterCodec)

	exec, err := remotecommand.NewSPDYExecutor(kc.config, "POST", req.URL())
	if err != nil {
		return err
	}
	return exec.Stream(remotecommand.StreamOptions{
		Stdin:  opts.Stdin,
		Stdout: opts.Stdout,
		Stderr: opts.Stdout,
		Tty:    opts.Tty,
	})
}

// GetContainers get containers for a given compose project
func (kc KubeClient) GetContainers(ctx context.Context, projectName string, all bool) ([]api.ContainerSummary, error) {
	fieldSelector := ""
	if !all {
		fieldSelector = "status.phase=Running"
	}

	pods, err := kc.client.CoreV1().Pods(kc.namespace).List(ctx, metav1.ListOptions{
		LabelSelector: fmt.Sprintf("%s=%s", api.ProjectLabel, projectName),
		FieldSelector: fieldSelector,
	})
	if err != nil {
		return nil, err
	}
	services := map[string][]api.PortPublisher{}
	result := []api.ContainerSummary{}
	for _, pod := range pods.Items {
		summary := podToContainerSummary(pod)
		serviceName := pod.GetObjectMeta().GetLabels()[api.ServiceLabel]
		ports, ok := services[serviceName]
		if !ok {
			s, err := kc.client.CoreV1().Services(kc.namespace).Get(ctx, serviceName, metav1.GetOptions{})
			if err != nil {
				if !strings.Contains(err.Error(), "not found") {
					return nil, err
				}
				result = append(result, summary)
				continue
			}
			ports = []api.PortPublisher{}
			if s != nil {
				if s.Spec.Type == corev1.ServiceTypeLoadBalancer {
					if len(s.Status.LoadBalancer.Ingress) > 0 {
						port := api.PortPublisher{URL: s.Status.LoadBalancer.Ingress[0].IP}
						if len(s.Spec.Ports) > 0 {
							port.URL = fmt.Sprintf("%s:%d", port.URL, s.Spec.Ports[0].Port)
							port.TargetPort = s.Spec.Ports[0].TargetPort.IntValue()
							port.Protocol = string(s.Spec.Ports[0].Protocol)
						}
						ports = append(ports, port)
					}
				}
			}
			services[serviceName] = ports
		}
		summary.Publishers = ports
		result = append(result, summary)
	}

	return result, nil
}

// GetLogs retrieves pod logs
func (kc *KubeClient) GetLogs(ctx context.Context, projectName string, consumer api.LogConsumer, follow bool) error {
	pods, err := kc.client.CoreV1().Pods(kc.namespace).List(ctx, metav1.ListOptions{
		LabelSelector: fmt.Sprintf("%s=%s", api.ProjectLabel, projectName),
	})
	if err != nil {
		return err
	}
	eg, ctx := errgroup.WithContext(ctx)
	for _, pod := range pods.Items {
		request := kc.client.CoreV1().Pods(kc.namespace).GetLogs(pod.Name, &corev1.PodLogOptions{Follow: follow})
		service := pod.Labels[api.ServiceLabel]
		w := utils.GetWriter(func(line string) {
			consumer.Log(pod.Name, service, line)
		})

		eg.Go(func() error {
			r, err := request.Stream(ctx)
			if err != nil {
				return err
			}

			defer r.Close() // nolint errcheck
			_, err = io.Copy(w, r)
			return err
		})
	}
	return eg.Wait()
}

// WaitForPodState blocks until pods reach desired state
func (kc KubeClient) WaitForPodState(ctx context.Context, opts WaitForStatusOptions) error {
	var timeout = time.Minute
	if opts.Timeout != nil {
		timeout = *opts.Timeout
	}

	errch := make(chan error, 1)
	done := make(chan bool)
	go func() {
		for {
			time.Sleep(500 * time.Millisecond)

			pods, err := kc.client.CoreV1().Pods(kc.namespace).List(ctx, metav1.ListOptions{
				LabelSelector: fmt.Sprintf("%s=%s", api.ProjectLabel, opts.ProjectName),
			})
			if err != nil {
				errch <- err
			}
			stateReached, servicePods, err := checkPodsState(opts.Services, pods.Items, opts.Status)
			if err != nil {
				errch <- err
			}
			if opts.Log != nil {
				for p, m := range servicePods {
					opts.Log(p, stateReached, m)
				}
			}

			if stateReached {
				done <- true
			}
		}
	}()

	select {
	case <-time.After(timeout):
		return fmt.Errorf("timeout: pods did not reach expected state")
	case err := <-errch:
		if err != nil {
			return err
		}
	case <-done:
		return nil
	}
	return nil
}

//MapPortsToLocalhost runs a port-forwarder daemon process
func (kc KubeClient) MapPortsToLocalhost(ctx context.Context, opts PortMappingOptions) error {
	stopChannel := make(chan struct{}, 1)
	readyChannel := make(chan struct{})

	eg, ctx := errgroup.WithContext(ctx)
	for serviceName, servicePorts := range opts.Services {
		serviceName, servicePorts := serviceName, servicePorts
		pod, err := kc.GetPod(ctx, opts.ProjectName, serviceName)
		if err != nil {
			return err
		}
		eg.Go(func() error {
			ports := []string{}
			for _, p := range servicePorts {
				ports = append(ports, fmt.Sprintf("%d:%d", p.PublishedPort, p.TargetPort))
			}

			req := kc.client.CoreV1().RESTClient().Post().
				Resource("pods").
				Name(pod.Name).
				Namespace(kc.namespace).
				SubResource("portforward")
			transport, upgrader, err := spdy.RoundTripperFor(kc.config)
			if err != nil {
				return err
			}
			dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", req.URL())
			fw, err := portforward.New(dialer, ports, stopChannel, readyChannel, os.Stdout, os.Stderr)
			if err != nil {
				return err
			}
			return fw.ForwardPorts()
		})
	}
	return eg.Wait()
}
<commit_msg>Fix container name used in kube log output<commit_after>// +build kube

/*
   Copyright 2020 Docker Compose CLI authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package client

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/docker/compose-cli/pkg/api"
	"github.com/docker/compose-cli/pkg/utils"

	"golang.org/x/sync/errgroup"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/portforward"
	"k8s.io/client-go/tools/remotecommand"
	"k8s.io/client-go/transport/spdy"
)

// KubeClient API to access kube objects
type KubeClient struct {
	client    *kubernetes.Clientset
	namespace string
	config    *rest.Config
	ioStreams genericclioptions.IOStreams
}

// NewKubeClient new kubernetes client
func NewKubeClient(config genericclioptions.RESTClientGetter) (*KubeClient, error) {
	restConfig, err := config.ToRESTConfig()
	if err != nil {
		return nil, err
	}

	clientset, err := kubernetes.NewForConfig(restConfig)
	if err != nil {
		return nil, fmt.Errorf("failed creating clientset. Error: %+v", err)
	}

	namespace, _, err := config.ToRawKubeConfigLoader().Namespace()
	if err != nil {
		return nil, err
	}

	return &KubeClient{
		client:    clientset,
		namespace: namespace,
		config:    restConfig,
		ioStreams: genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr},
	}, nil
}

// GetPod retrieves a service pod
func (kc KubeClient) GetPod(ctx context.Context, projectName, serviceName string) (*corev1.Pod, error) {
	pods, err := kc.client.CoreV1().Pods(kc.namespace).List(ctx, metav1.ListOptions{
		LabelSelector: fmt.Sprintf("%s=%s", api.ProjectLabel, projectName),
	})
	if err != nil {
		return nil, err
	}
	if pods == nil {
		return nil, nil
	}
	var pod corev1.Pod
	for _, p := range pods.Items {
		service := p.Labels[api.ServiceLabel]
		if service == serviceName {
			pod = p
			break
		}
	}
	return &pod, nil
}

// Exec executes a command in a container
func (kc KubeClient) Exec(ctx context.Context, projectName string, opts api.RunOptions) error {
	pod, err := kc.GetPod(ctx, projectName, opts.Service)
	if err != nil || pod == nil {
		return err
	}
	if len(pod.Spec.Containers) == 0 {
		return fmt.Errorf("no containers running in pod %s", pod.Name)
	}
	// get first container in the pod
	container := &pod.Spec.Containers[0]
	containerName := container.Name

	req := kc.client.CoreV1().RESTClient().Post().
		Resource("pods").
		Name(pod.Name).
		Namespace(kc.namespace).
		SubResource("exec")

	option := &corev1.PodExecOptions{
		Container: containerName,
		Command:   opts.Command,
		Stdin:     true,
		Stdout:    true,
		Stderr:    true,
		TTY:       opts.Tty,
	}

	if opts.Stdin == nil {
		option.Stdin = false
	}

	scheme := runtime.NewScheme()
	if err := corev1.AddToScheme(scheme); err != nil {
		return fmt.Errorf("error adding to scheme: %v", err)
	}
	parameterCodec := runtime.NewParameterCodec(scheme)
	req.VersionedParams(option, parameterCodec)

	exec, err := remotecommand.NewSPDYExecutor(kc.config, "POST", req.URL())
	if err != nil {
		return err
	}
	return exec.Stream(remotecommand.StreamOptions{
		Stdin:  opts.Stdin,
		Stdout: opts.Stdout,
		Stderr: opts.Stdout,
		Tty:    opts.Tty,
	})
}

// GetContainers get containers for a given compose project
func (kc KubeClient) GetContainers(ctx context.Context, projectName string, all bool) ([]api.ContainerSummary, error) {
	fieldSelector := ""
	if !all {
		fieldSelector = "status.phase=Running"
	}

	pods, err := kc.client.CoreV1().Pods(kc.namespace).List(ctx, metav1.ListOptions{
		LabelSelector: fmt.Sprintf("%s=%s", api.ProjectLabel, projectName),
		FieldSelector: fieldSelector,
	})
	if err != nil {
		return nil, err
	}
	services := map[string][]api.PortPublisher{}
	result := []api.ContainerSummary{}
	for _, pod := range pods.Items {
		summary := podToContainerSummary(pod)
		serviceName := pod.GetObjectMeta().GetLabels()[api.ServiceLabel]
		ports, ok := services[serviceName]
		if !ok {
			s, err := kc.client.CoreV1().Services(kc.namespace).Get(ctx, serviceName, metav1.GetOptions{})
			if err != nil {
				if !strings.Contains(err.Error(), "not found") {
					return nil, err
				}
				result = append(result, summary)
				continue
			}
			ports = []api.PortPublisher{}
			if s != nil {
				if s.Spec.Type == corev1.ServiceTypeLoadBalancer {
					if len(s.Status.LoadBalancer.Ingress) > 0 {
						port := api.PortPublisher{URL: s.Status.LoadBalancer.Ingress[0].IP}
						if len(s.Spec.Ports) > 0 {
							port.URL = fmt.Sprintf("%s:%d", port.URL, s.Spec.Ports[0].Port)
							port.TargetPort = s.Spec.Ports[0].TargetPort.IntValue()
							port.Protocol = string(s.Spec.Ports[0].Protocol)
						}
						ports = append(ports, port)
					}
				}
			}
			services[serviceName] = ports
		}
		summary.Publishers = ports
		result = append(result, summary)
	}

	return result, nil
}

// GetLogs retrieves pod logs
func (kc *KubeClient) GetLogs(ctx context.Context, projectName string, consumer api.LogConsumer, follow bool) error {
	pods, err := kc.client.CoreV1().Pods(kc.namespace).List(ctx, metav1.ListOptions{
		LabelSelector: fmt.Sprintf("%s=%s", api.ProjectLabel, projectName),
	})
	if err != nil {
		return err
	}
	eg, ctx := errgroup.WithContext(ctx)
	for _, pod := range pods.Items {
		podName := pod.Name
		request := kc.client.CoreV1().Pods(kc.namespace).GetLogs(podName, &corev1.PodLogOptions{Follow: follow})
		service := pod.Labels[api.ServiceLabel]
		w := utils.GetWriter(func(line string) {
			consumer.Log(podName, service, line)
		})

		eg.Go(func() error {
			r, err := request.Stream(ctx)
			if err != nil {
				return err
			}

			defer r.Close() // nolint errcheck
			_, err = io.Copy(w, r)
			return err
		})
	}
	return eg.Wait()
}

// WaitForPodState blocks until pods reach desired state
func (kc KubeClient) WaitForPodState(ctx context.Context, opts WaitForStatusOptions) error {
	var timeout = time.Minute
	if opts.Timeout != nil {
		timeout = *opts.Timeout
	}

	errch := make(chan error, 1)
	done := make(chan bool)
	go func() {
		for {
			time.Sleep(500 * time.Millisecond)

			pods, err := kc.client.CoreV1().Pods(kc.namespace).List(ctx, metav1.ListOptions{
				LabelSelector: fmt.Sprintf("%s=%s", api.ProjectLabel, opts.ProjectName),
			})
			if err != nil {
				errch <- err
			}
			stateReached, servicePods, err := checkPodsState(opts.Services, pods.Items, opts.Status)
			if err != nil {
				errch <- err
			}
			if opts.Log != nil {
				for p, m := range servicePods {
					opts.Log(p, stateReached, m)
				}
			}

			if stateReached {
				done <- true
			}
		}
	}()

	select {
	case <-time.After(timeout):
		return fmt.Errorf("timeout: pods did not reach expected state")
	case err := <-errch:
		if err != nil {
			return err
		}
	case <-done:
		return nil
	}
	return nil
}

//MapPortsToLocalhost runs a port-forwarder daemon process
func (kc KubeClient) MapPortsToLocalhost(ctx context.Context, opts PortMappingOptions) error {
	stopChannel := make(chan struct{}, 1)
	readyChannel := make(chan struct{})

	eg, ctx := errgroup.WithContext(ctx)
	for serviceName, servicePorts := range opts.Services {
		serviceName, servicePorts := serviceName, servicePorts
		pod, err := kc.GetPod(ctx, opts.ProjectName, serviceName)
		if err != nil {
			return err
		}
		eg.Go(func() error {
			ports := []string{}
			for _, p := range servicePorts {
				ports = append(ports, fmt.Sprintf("%d:%d", p.PublishedPort, p.TargetPort))
			}

			req := kc.client.CoreV1().RESTClient().Post().
				Resource("pods").
				Name(pod.Name).
				Namespace(kc.namespace).
				SubResource("portforward")
			transport, upgrader, err := spdy.RoundTripperFor(kc.config)
			if err != nil {
				return err
			}
			dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", req.URL())
			fw, err := portforward.New(dialer, ports, stopChannel, readyChannel, os.Stdout, os.Stderr)
			if err != nil {
				return err
			}
			return fw.ForwardPorts()
		})
	}
	return eg.Wait()
}
<|endoftext|>