<commit_before>package watch

import (
	"fmt"
	"log"
	"sync"
	"time"

	dep "github.com/hashicorp/consul-template/dependency"
	"github.com/hashicorp/consul/api"
)

// RetryFunc is a function that defines the retry for a given watcher. The
// function parameter is the current retry (which might be nil), and the
// return value is the new retry. In this way, you can build complex retry
// functions that are based off the previous values.
type RetryFunc func(time.Duration) time.Duration

// DefaultRetryFunc is the default return function, which just echos whatever
// duration it was given.
var DefaultRetryFunc RetryFunc = func(t time.Duration) time.Duration {
	return t
}

// dataBufferSize is the default number of views to process in a batch.
const dataBufferSize = 2048

// Watcher is a top-level manager for views that poll Consul for data.
type Watcher struct {
	sync.Mutex

	// DataCh is the chan where Views will be published.
	DataCh chan *View

	// ErrCh is the chan where any errors will be published.
	ErrCh chan error

	// FinishCh is the chan where the watcher reports it is "done".
	FinishCh chan struct{}

	// config is the internal configuration of this watcher.
	config *WatcherConfig

	// depViewMap is a map of Templates to Views. Templates are keyed by
	// HashCode().
	depViewMap map[string]*View
}

// WatcherConfig is the configuration for a particular Watcher.
type WatcherConfig struct {
	// Client is the mechanism for communicating with the Consul API.
	Client *api.Client

	// Once is used to determine if the views should poll for data exactly once.
	Once bool

	// MaxStale is the maximum staleness of a query. If specified, Consul will
	// distribute work among all servers instead of just the leader. Specifying
	// this option assumes the use of AllowStale.
	MaxStale time.Duration

	// RetryFunc is a RetryFunc that represents the way retrys and backoffs
	// should occur.
	RetryFunc RetryFunc
}

// NewWatcher creates a new watcher using the given API client.
func NewWatcher(config *WatcherConfig) (*Watcher, error) {
	watcher := &Watcher{config: config}
	if err := watcher.init(); err != nil {
		return nil, err
	}

	return watcher, nil
}

// Add adds the given dependency to the list of monitored depedencies
// and start the associated view. If the dependency already exists, no action is
// taken.
//
// If the Dependency already existed, it this function will return false. If the
// view was successfully created, it will return true. If an error occurs while
// creating the view, it will be returned here (but future errors returned by
// the view will happen on the channel).
func (w *Watcher) Add(d dep.Dependency) (bool, error) {
	w.Lock()
	defer w.Unlock()

	log.Printf("[INFO] (watcher) adding %s", d.Display())

	if _, ok := w.depViewMap[d.HashCode()]; ok {
		log.Printf("[DEBUG] (watcher) %s already exists, skipping", d.Display())
		return false, nil
	}

	v, err := NewView(w.config, d)
	if err != nil {
		return false, err
	}

	log.Printf("[DEBUG] (watcher) %s starting", d.Display())

	w.depViewMap[d.HashCode()] = v
	go v.poll(w.DataCh, w.ErrCh)

	return true, nil
}

// Watching determines if the given dependency is being watched.
func (w *Watcher) Watching(d dep.Dependency) bool {
	w.Lock()
	defer w.Unlock()

	_, ok := w.depViewMap[d.HashCode()]
	return ok
}

// Remove removes the given dependency from the list and stops the
// associated View. If a View for the given dependency does not exist, this
// function will return false. If the View does exist, this function will return
// true upon successful deletion.
func (w *Watcher) Remove(d dep.Dependency) bool {
	w.Lock()
	defer w.Unlock()

	log.Printf("[INFO] (watcher) removing %s", d.Display())

	if view, ok := w.depViewMap[d.HashCode()]; ok {
		log.Printf("[DEBUG] (watcher) actually removing %s", d.Display())
		view.stop()
		delete(w.depViewMap, d.HashCode())
		return true
	}

	log.Printf("[DEBUG] (watcher) %s did not exist, skipping", d.Display())
	return false
}

// Size returns the number of views this watcher is watching.
func (w *Watcher) Size() int {
	w.Lock()
	defer w.Unlock()

	log.Printf("[INFO] (watcher) getting size")

	return len(w.depViewMap)
}

// Stop halts this watcher and any currently polling views immediately. If a
// view was in the middle of a poll, no data will be returned.
func (w *Watcher) Stop() {
	w.Lock()
	defer w.Unlock()

	log.Printf("[INFO] (watcher) stopping all views")

	for _, view := range w.depViewMap {
		log.Printf("[DEBUG] (watcher) stopping %s", view.Dependency.Display())
		view.stop()
	}

	// Reset the map to have no views
	w.depViewMap = make(map[string]*View)
}

// init sets up the initial values for the watcher.
func (w *Watcher) init() error {
	if w.config == nil {
		return fmt.Errorf("watcher: missing config")
	}

	if w.config.RetryFunc == nil {
		w.config.RetryFunc = DefaultRetryFunc
	}

	// Setup the channels
	w.DataCh = make(chan *View, dataBufferSize)
	w.ErrCh = make(chan error)
	w.FinishCh = make(chan struct{})

	// Setup our map of dependencies to views
	w.depViewMap = make(map[string]*View)

	return nil
}
<commit_msg>Remove verbose log  message<commit_after>package watch

import (
	"fmt"
	"log"
	"sync"
	"time"

	dep "github.com/hashicorp/consul-template/dependency"
	"github.com/hashicorp/consul/api"
)

// RetryFunc is a function that defines the retry for a given watcher. The
// function parameter is the current retry (which might be nil), and the
// return value is the new retry. In this way, you can build complex retry
// functions that are based off the previous values.
type RetryFunc func(time.Duration) time.Duration

// DefaultRetryFunc is the default return function, which just echos whatever
// duration it was given.
var DefaultRetryFunc RetryFunc = func(t time.Duration) time.Duration {
	return t
}

// dataBufferSize is the default number of views to process in a batch.
const dataBufferSize = 2048

// Watcher is a top-level manager for views that poll Consul for data.
type Watcher struct {
	sync.Mutex

	// DataCh is the chan where Views will be published.
	DataCh chan *View

	// ErrCh is the chan where any errors will be published.
	ErrCh chan error

	// FinishCh is the chan where the watcher reports it is "done".
	FinishCh chan struct{}

	// config is the internal configuration of this watcher.
	config *WatcherConfig

	// depViewMap is a map of Templates to Views. Templates are keyed by
	// HashCode().
	depViewMap map[string]*View
}

// WatcherConfig is the configuration for a particular Watcher.
type WatcherConfig struct {
	// Client is the mechanism for communicating with the Consul API.
	Client *api.Client

	// Once is used to determine if the views should poll for data exactly once.
	Once bool

	// MaxStale is the maximum staleness of a query. If specified, Consul will
	// distribute work among all servers instead of just the leader. Specifying
	// this option assumes the use of AllowStale.
	MaxStale time.Duration

	// RetryFunc is a RetryFunc that represents the way retrys and backoffs
	// should occur.
	RetryFunc RetryFunc
}

// NewWatcher creates a new watcher using the given API client.
func NewWatcher(config *WatcherConfig) (*Watcher, error) {
	watcher := &Watcher{config: config}
	if err := watcher.init(); err != nil {
		return nil, err
	}

	return watcher, nil
}

// Add adds the given dependency to the list of monitored depedencies
// and start the associated view. If the dependency already exists, no action is
// taken.
//
// If the Dependency already existed, it this function will return false. If the
// view was successfully created, it will return true. If an error occurs while
// creating the view, it will be returned here (but future errors returned by
// the view will happen on the channel).
func (w *Watcher) Add(d dep.Dependency) (bool, error) {
	w.Lock()
	defer w.Unlock()

	log.Printf("[INFO] (watcher) adding %s", d.Display())

	if _, ok := w.depViewMap[d.HashCode()]; ok {
		log.Printf("[DEBUG] (watcher) %s already exists, skipping", d.Display())
		return false, nil
	}

	v, err := NewView(w.config, d)
	if err != nil {
		return false, err
	}

	log.Printf("[DEBUG] (watcher) %s starting", d.Display())

	w.depViewMap[d.HashCode()] = v
	go v.poll(w.DataCh, w.ErrCh)

	return true, nil
}

// Watching determines if the given dependency is being watched.
func (w *Watcher) Watching(d dep.Dependency) bool {
	w.Lock()
	defer w.Unlock()

	_, ok := w.depViewMap[d.HashCode()]
	return ok
}

// Remove removes the given dependency from the list and stops the
// associated View. If a View for the given dependency does not exist, this
// function will return false. If the View does exist, this function will return
// true upon successful deletion.
func (w *Watcher) Remove(d dep.Dependency) bool {
	w.Lock()
	defer w.Unlock()

	log.Printf("[INFO] (watcher) removing %s", d.Display())

	if view, ok := w.depViewMap[d.HashCode()]; ok {
		log.Printf("[DEBUG] (watcher) actually removing %s", d.Display())
		view.stop()
		delete(w.depViewMap, d.HashCode())
		return true
	}

	log.Printf("[DEBUG] (watcher) %s did not exist, skipping", d.Display())
	return false
}

// Size returns the number of views this watcher is watching.
func (w *Watcher) Size() int {
	w.Lock()
	defer w.Unlock()
	return len(w.depViewMap)
}

// Stop halts this watcher and any currently polling views immediately. If a
// view was in the middle of a poll, no data will be returned.
func (w *Watcher) Stop() {
	w.Lock()
	defer w.Unlock()

	log.Printf("[INFO] (watcher) stopping all views")

	for _, view := range w.depViewMap {
		log.Printf("[DEBUG] (watcher) stopping %s", view.Dependency.Display())
		view.stop()
	}

	// Reset the map to have no views
	w.depViewMap = make(map[string]*View)
}

// init sets up the initial values for the watcher.
func (w *Watcher) init() error {
	if w.config == nil {
		return fmt.Errorf("watcher: missing config")
	}

	if w.config.RetryFunc == nil {
		w.config.RetryFunc = DefaultRetryFunc
	}

	// Setup the channels
	w.DataCh = make(chan *View, dataBufferSize)
	w.ErrCh = make(chan error)
	w.FinishCh = make(chan struct{})

	// Setup our map of dependencies to views
	w.depViewMap = make(map[string]*View)

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"io/ioutil"
	"mime/multipart"
	"testing"
	"time"
)

func TestEncode(t *testing.T) {
	msg, err := readTestMail("attachments.eml")

	if err != nil {
		t.Fatal(err)
	}
	buf := bytes.NewBuffer(nil)
	enc := NewMultipartEncoder(buf)
	mail := NewMail("bill@example.com", "tina@example.org", msg)

	if err := enc.Encode("mail", mail); err != nil {
		t.Fatal(err)
	}
	enc.Close()

	f, err := multipart.NewReader(buf, enc.Boundary()).ReadForm(int64(10 << 20))

	if err != nil {
		t.Fatal(err)
	}

	if n := len(f.Value["mail[sender]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[sender]"][0]; v != "bill@example.com" {
		t.Fatalf("\"bill@example.org\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[recipient]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[recipient]"][0]; v != "tina@example.org" {
		t.Fatalf("\"tina@example.org\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][from][][name]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][from][][name]"][0]; v != "Bob" {
		t.Fatalf("\"Bob\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][from][][email]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][from][][email]"][0]; v != "bob@example.org" {
		t.Fatalf("\"bob@example.org\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][to][][email]"]); n != 2 {
		t.Fatalf("2 != %d", n)
	}

	if v := f.Value["mail[message][to][][email]"][0]; v != "alice@example.com" {
		t.Fatalf("\"alice@example.com\" != \"%s\"", v)
	}

	if v := f.Value["mail[message][to][][email]"][1]; v != "tina@example.com" {
		t.Fatalf("\"tina@example.com\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][cc][][email]"]); n != 0 {
		t.Fatalf("0 != %d", n)
	}

	if n := len(f.Value["mail[message][bcc][][email]"]); n != 0 {
		t.Fatalf("0 != %d", n)
	}

	if n := len(f.Value["mail[message][reply_to][][email]"]); n != 0 {
		t.Fatalf("0 != %d", n)
	}

	if n := len(f.Value["mail[message][subject]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][subject]"][0]; v != "Re: This is just a test" {
		t.Fatalf("\"Re: This is just a test\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][date]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}
	loc, err := time.LoadLocation("Europe/Berlin")

	if err != nil {
		t.Fatal(err)
	}
	date := time.Date(2016, 4, 11, 17, 44, 9, 0, loc).Format(time.RFC3339)

	if v := f.Value["mail[message][date]"][0]; v != date {
		t.Fatalf("\"%s\" != \"%s\"", date, v)
	}

	if n := len(f.Value["mail[message][message_id]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][message_id]"][0]; v != "<5727b6c4@example.org>" {
		t.Fatalf("\"<5727b6c4@example.org>\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][in_reply_to]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][in_reply_to]"][0]; v != "<8b6ea071@example.com>" {
		t.Fatalf("\"<8b6ea071@example.com>\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][references][]"]); n != 3 {
		t.Fatalf("3 != %d", n)
	}

	if v := f.Value["mail[message][references][]"][0]; v != "<8ca8a3e3@example.com>" {
		t.Fatalf("\"<8ca8a3e3@example.com>\" != \"%s\"", v)
	}

	if v := f.Value["mail[message][references][]"][2]; v != "<8b6ea071@example.com>" {
		t.Fatalf("\"<8b6ea071@example.com>\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][text]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}
	text := `Hey Alice, thanks for your test mail!

> Hey Bob,
>
> this is just a test...
>
> Cheers, Alice
`

	if v := f.Value["mail[message][text]"][0]; v != text {
		t.Fatalf("unexpected text: \"%s\"", v)
	}

	if n := len(f.Value["mail[message][html]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][html]"][0]; v != "" {
		t.Fatalf("unexpected html: \"%s\"", v)
	}

	if n := len(f.File["mail[message][attachments][]"]); n != 4 {
		t.Fatalf("4 != %d", n)
	}

	for _, a := range f.File["mail[message][attachments][]"] {
		orig, err := readAttachment(a.Filename)

		if err != nil {
			t.Fatal(err)
		}
		file, err := a.Open()

		if err != nil {
			t.Fatal(err)
		}
		body, err := ioutil.ReadAll(file)

		if err != nil {
			t.Fatal(err)
		}

		if !bytes.Equal(orig, body) {
			t.Fatal("unexpected body for: %s", a.Filename)
		}
	}
}
<commit_msg>fix multipart encoder test<commit_after>package main

import (
	"bytes"
	"io/ioutil"
	"mime/multipart"
	"testing"
	"time"
)

func TestEncode(t *testing.T) {
	msg, err := readTestMail("attachments.eml")

	if err != nil {
		t.Fatal(err)
	}
	buf := bytes.NewBuffer(nil)
	enc := NewMultipartEncoder(buf)
	mail := NewMail("bill@example.com", "tina@example.org", msg)

	if err := enc.Encode("mail", mail); err != nil {
		t.Fatal(err)
	}
	enc.Close()

	f, err := multipart.NewReader(buf, enc.Boundary()).ReadForm(int64(10 << 20))

	if err != nil {
		t.Fatal(err)
	}

	if n := len(f.Value["mail[sender]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[sender]"][0]; v != "bill@example.com" {
		t.Fatalf("\"bill@example.org\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[recipient]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[recipient]"][0]; v != "tina@example.org" {
		t.Fatalf("\"tina@example.org\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][from][][name]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][from][][name]"][0]; v != "Bob" {
		t.Fatalf("\"Bob\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][from][][email]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][from][][email]"][0]; v != "bob@example.org" {
		t.Fatalf("\"bob@example.org\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][to][][email]"]); n != 2 {
		t.Fatalf("2 != %d", n)
	}

	if v := f.Value["mail[message][to][][email]"][0]; v != "alice@example.com" {
		t.Fatalf("\"alice@example.com\" != \"%s\"", v)
	}

	if v := f.Value["mail[message][to][][email]"][1]; v != "tina@example.com" {
		t.Fatalf("\"tina@example.com\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][cc][][email]"]); n != 0 {
		t.Fatalf("0 != %d", n)
	}

	if n := len(f.Value["mail[message][bcc][][email]"]); n != 0 {
		t.Fatalf("0 != %d", n)
	}

	if n := len(f.Value["mail[message][reply_to][][email]"]); n != 0 {
		t.Fatalf("0 != %d", n)
	}

	if n := len(f.Value["mail[message][subject]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][subject]"][0]; v != "Re: This is just a test" {
		t.Fatalf("\"Re: This is just a test\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][date]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}
	loc, err := time.LoadLocation("Europe/Berlin")

	if err != nil {
		t.Fatal(err)
	}
	date := time.Date(2016, 4, 11, 17, 44, 9, 0, loc).Format(time.RFC3339)

	if v := f.Value["mail[message][date]"][0]; v != date {
		t.Fatalf("\"%s\" != \"%s\"", date, v)
	}

	if n := len(f.Value["mail[message][message_id]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][message_id]"][0]; v != "<5727b6c4@example.org>" {
		t.Fatalf("\"<5727b6c4@example.org>\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][in_reply_to]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][in_reply_to]"][0]; v != "<8b6ea071@example.com>" {
		t.Fatalf("\"<8b6ea071@example.com>\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][references][]"]); n != 3 {
		t.Fatalf("3 != %d", n)
	}

	if v := f.Value["mail[message][references][]"][0]; v != "<8ca8a3e3@example.com>" {
		t.Fatalf("\"<8ca8a3e3@example.com>\" != \"%s\"", v)
	}

	if v := f.Value["mail[message][references][]"][2]; v != "<8b6ea071@example.com>" {
		t.Fatalf("\"<8b6ea071@example.com>\" != \"%s\"", v)
	}

	if n := len(f.Value["mail[message][text]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}
	text := `Hey Alice, thanks for your test mail!

> Hey Bob,
>
> this is just a test...
>
> Cheers, Alice
`

	if v := f.Value["mail[message][text]"][0]; v != text {
		t.Fatalf("unexpected text: \"%s\"", v)
	}

	if n := len(f.Value["mail[message][html]"]); n != 1 {
		t.Fatalf("1 != %d", n)
	}

	if v := f.Value["mail[message][html]"][0]; v != "" {
		t.Fatalf("unexpected html: \"%s\"", v)
	}

	if n := len(f.File["mail[message][attachments][]"]); n != 4 {
		t.Fatalf("4 != %d", n)
	}

	for _, a := range f.File["mail[message][attachments][]"] {
		orig, err := readAttachment(a.Filename)

		if err != nil {
			t.Fatal(err)
		}
		file, err := a.Open()

		if err != nil {
			t.Fatal(err)
		}
		body, err := ioutil.ReadAll(file)

		if err != nil {
			t.Fatal(err)
		}

		if !bytes.Equal(orig, body) {
			t.Fatalf("unexpected body for: %s", a.Filename)
		}
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2018 The Knative 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 dispatcher

import (
	"context"
	"errors"
	"fmt"
	nethttp "net/http"
	"net/url"
	"sync"
	"sync/atomic"

	"github.com/Shopify/sarama"
	"github.com/cloudevents/sdk-go/v2/binding"
	protocolkafka "github.com/cloudevents/sdk-go/v2/protocol/kafka_sarama"
	"github.com/google/go-cmp/cmp"
	"go.uber.org/zap"
	"k8s.io/apimachinery/pkg/types"
	eventingduck "knative.dev/eventing/pkg/apis/duck/v1beta1"
	eventingchannels "knative.dev/eventing/pkg/channel"
	"knative.dev/eventing/pkg/channel/multichannelfanout"
	"knative.dev/eventing/pkg/kncloudevents"

	"knative.dev/eventing-contrib/kafka/channel/pkg/utils"
	"knative.dev/eventing-contrib/kafka/common/pkg/kafka"
)

type KafkaDispatcher struct {
	// TODO: config doesn't have to be atomic as it is read and updated using updateLock.
	config           atomic.Value
	hostToChannelMap atomic.Value
	// hostToChannelMapLock is used to update hostToChannelMap
	hostToChannelMapLock sync.Mutex

	messageSender *kncloudevents.HttpMessageSender
	receiver      *eventingchannels.MessageReceiver
	dispatcher    *eventingchannels.MessageDispatcherImpl

	kafkaAsyncProducer   sarama.AsyncProducer
	channelSubscriptions map[eventingchannels.ChannelReference][]types.UID
	subsConsumerGroups   map[types.UID]sarama.ConsumerGroup
	subscriptions        map[types.UID]subscription
	// consumerUpdateLock must be used to update kafkaConsumers
	consumerUpdateLock   sync.Mutex
	kafkaConsumerFactory kafka.KafkaConsumerGroupFactory

	topicFunc TopicFunc
	logger    *zap.Logger
}

func NewDispatcher(ctx context.Context, args *KafkaDispatcherArgs) (*KafkaDispatcher, error) {
	conf := sarama.NewConfig()
	conf.Version = sarama.V2_0_0_0
	conf.ClientID = args.ClientID
	conf.Consumer.Return.Errors = true // Returns the errors in ConsumerGroup#Errors() https://godoc.org/github.com/Shopify/sarama#ConsumerGroup
	client, err := sarama.NewClient(args.Brokers, conf)

	if err != nil {
		return nil, fmt.Errorf("unable to create kafka client: %v", err)
	}

	producer, err := sarama.NewAsyncProducerFromClient(client)
	if err != nil {
		return nil, fmt.Errorf("unable to create kafka producer: %v", err)
	}

	messageSender, err := kncloudevents.NewHttpMessageSender(args.KnCEConnectionArgs, "")
	if err != nil {
		args.Logger.Fatal("failed to create message sender", zap.Error(err))
	}

	dispatcher := &KafkaDispatcher{
		dispatcher:           eventingchannels.NewMessageDispatcher(args.Logger),
		kafkaConsumerFactory: kafka.NewConsumerGroupFactory(client),
		channelSubscriptions: make(map[eventingchannels.ChannelReference][]types.UID),
		subsConsumerGroups:   make(map[types.UID]sarama.ConsumerGroup),
		subscriptions:        make(map[types.UID]subscription),
		kafkaAsyncProducer:   producer,
		logger:               args.Logger,
		messageSender:        messageSender,
		topicFunc:            args.TopicFunc,
	}
	receiverFunc, err := eventingchannels.NewMessageReceiver(
		func(ctx context.Context, channel eventingchannels.ChannelReference, message binding.Message, transformers []binding.Transformer, _ nethttp.Header) error {
			kafkaProducerMessage := sarama.ProducerMessage{
				Topic: dispatcher.topicFunc(utils.KafkaChannelSeparator, channel.Namespace, channel.Name),
			}

			dispatcher.logger.Debug("Received a new message from MessageReceiver, dispatching to Kafka", zap.Any("channel", channel))
			err := protocolkafka.WriteProducerMessage(ctx, message, &kafkaProducerMessage, transformers...)
			if err != nil {
				return err
			}

			dispatcher.kafkaAsyncProducer.Input() <- &kafkaProducerMessage
			return nil
		},
		args.Logger,
		eventingchannels.ResolveMessageChannelFromHostHeader(dispatcher.getChannelReferenceFromHost))
	if err != nil {
		return nil, err
	}

	dispatcher.receiver = receiverFunc
	dispatcher.setConfig(&multichannelfanout.Config{})
	dispatcher.setHostToChannelMap(map[string]eventingchannels.ChannelReference{})
	return dispatcher, nil
}

type TopicFunc func(separator, namespace, name string) string

type KafkaDispatcherArgs struct {
	KnCEConnectionArgs *kncloudevents.ConnectionArgs
	ClientID           string
	Brokers            []string
	TopicFunc          TopicFunc
	Logger             *zap.Logger
}

type consumerMessageHandler struct {
	logger     *zap.Logger
	sub        subscription
	dispatcher *eventingchannels.MessageDispatcherImpl
}

func (c consumerMessageHandler) Handle(ctx context.Context, consumerMessage *sarama.ConsumerMessage) (bool, error) {
	defer func() {
		if r := recover(); r != nil {
			c.logger.Warn("Panic happened while handling a message",
				zap.String("topic", consumerMessage.Topic),
				zap.String("sub", string(c.sub.UID)),
				zap.Any("panic value", r),
			)
		}
	}()
	message := protocolkafka.NewMessageFromConsumerMessage(consumerMessage)
	if message.ReadEncoding() == binding.EncodingUnknown {
		return false, errors.New("received a message with unknown encoding")
	}
	var destination *url.URL
	if !c.sub.SubscriberURI.IsEmpty() {
		destination = c.sub.SubscriberURI.URL()
	}
	var reply *url.URL
	if !c.sub.ReplyURI.IsEmpty() {
		reply = c.sub.ReplyURI.URL()
	}
	var deadLetter *url.URL
	if c.sub.Delivery != nil && c.sub.Delivery.DeadLetterSink != nil && !c.sub.Delivery.DeadLetterSink.URI.IsEmpty() {
		deadLetter = c.sub.Delivery.DeadLetterSink.URI.URL()
	}
	c.logger.Debug("Going to dispatch the message",
		zap.String("topic", consumerMessage.Topic),
		zap.String("sub", string(c.sub.UID)),
	)
	err := c.dispatcher.DispatchMessage(context.Background(), message, nil, destination, reply, deadLetter)
	// NOTE: only return `true` here if DispatchMessage actually delivered the message.
	return err == nil, err
}

var _ kafka.KafkaConsumerHandler = (*consumerMessageHandler)(nil)

type subscription struct {
	eventingduck.SubscriberSpec
	Namespace string
	Name      string
}

// configDiff diffs the new config with the existing config. If there are no differences, then the
// empty string is returned. If there are differences, then a non-empty string is returned
// describing the differences.
func (d *KafkaDispatcher) configDiff(updated *multichannelfanout.Config) string {
	return cmp.Diff(d.getConfig(), updated)
}

// UpdateKafkaConsumers will be called by new CRD based kafka channel dispatcher controller.
func (d *KafkaDispatcher) UpdateKafkaConsumers(config *multichannelfanout.Config) (map[eventingduck.SubscriberSpec]error, error) {
	if config == nil {
		return nil, fmt.Errorf("nil config")
	}

	d.consumerUpdateLock.Lock()
	defer d.consumerUpdateLock.Unlock()

	var newSubs []types.UID
	failedToSubscribe := make(map[eventingduck.SubscriberSpec]error)
	for _, cc := range config.ChannelConfigs {
		channelRef := eventingchannels.ChannelReference{
			Name:      cc.Name,
			Namespace: cc.Namespace,
		}
		for _, subSpec := range cc.FanoutConfig.Subscriptions {
			sub := newSubscription(subSpec, string(subSpec.UID), cc.Namespace)
			newSubs = append(newSubs, sub.UID)

			// Check if sub already exists
			exists := false
			for _, s := range d.channelSubscriptions[channelRef] {
				if s == sub.UID {
					exists = true
				}
			}

			if !exists {
				// only subscribe when not exists in channel-subscriptions map
				// do not need to resubscribe every time channel fanout config is updated
				if err := d.subscribe(channelRef, sub); err != nil {
					failedToSubscribe[subSpec] = err
				}
			}
		}
	}

	d.logger.Debug("Number of new subs", zap.Any("subs", len(newSubs)))
	d.logger.Debug("Number of subs failed to subscribe", zap.Any("subs", len(failedToSubscribe)))

	// Unsubscribe and close consumer for any deleted subscriptions
	for channelRef, subs := range d.channelSubscriptions {
		for _, oldSub := range subs {
			removedSub := true
			for _, s := range newSubs {
				if s == oldSub {
					removedSub = false
				}
			}

			if removedSub {
				if err := d.unsubscribe(channelRef, d.subscriptions[oldSub]); err != nil {
					return nil, err
				}
			}
		}
		d.channelSubscriptions[channelRef] = newSubs
	}
	return failedToSubscribe, nil
}

// UpdateHostToChannelMap will be called by new CRD based kafka channel dispatcher controller.
func (d *KafkaDispatcher) UpdateHostToChannelMap(config *multichannelfanout.Config) error {
	if config == nil {
		return errors.New("nil config")
	}

	d.hostToChannelMapLock.Lock()
	defer d.hostToChannelMapLock.Unlock()

	hcMap, err := createHostToChannelMap(config)
	if err != nil {
		return err
	}

	d.setHostToChannelMap(hcMap)
	return nil
}

func createHostToChannelMap(config *multichannelfanout.Config) (map[string]eventingchannels.ChannelReference, error) {
	hcMap := make(map[string]eventingchannels.ChannelReference, len(config.ChannelConfigs))
	for _, cConfig := range config.ChannelConfigs {
		if cr, ok := hcMap[cConfig.HostName]; ok {
			return nil, fmt.Errorf(
				"duplicate hostName found. Each channel must have a unique host header. HostName:%s, channel:%s.%s, channel:%s.%s",
				cConfig.HostName,
				cConfig.Namespace,
				cConfig.Name,
				cr.Namespace,
				cr.Name)
		}
		hcMap[cConfig.HostName] = eventingchannels.ChannelReference{Name: cConfig.Name, Namespace: cConfig.Namespace}
	}
	return hcMap, nil
}

// Start starts the kafka dispatcher's message processing.
func (d *KafkaDispatcher) Start(ctx context.Context) error {
	if d.receiver == nil {
		return fmt.Errorf("message receiver is not set")
	}

	if d.kafkaAsyncProducer == nil {
		return fmt.Errorf("kafkaAsyncProducer is not set")
	}

	go func() {
		for {
			select {
			case e := <-d.kafkaAsyncProducer.Errors():
				d.logger.Warn("Got", zap.Error(e))
			case s := <-d.kafkaAsyncProducer.Successes():
				d.logger.Info("Sent", zap.Any("success", s))
			case <-ctx.Done():
				return
			}
		}
	}()

	return d.receiver.Start(ctx)
}

// subscribe reads kafkaConsumers which gets updated in UpdateConfig in a separate go-routine.
// subscribe must be called under updateLock.
func (d *KafkaDispatcher) subscribe(channelRef eventingchannels.ChannelReference, sub subscription) error {
	d.logger.Info("Subscribing", zap.Any("channelRef", channelRef), zap.Any("subscription", sub))

	topicName := d.topicFunc(utils.KafkaChannelSeparator, channelRef.Namespace, channelRef.Name)
	groupID := fmt.Sprintf("kafka.%s.%s.%s", sub.Namespace, channelRef.Name, sub.Name)

	handler := &consumerMessageHandler{d.logger, sub, d.dispatcher}

	consumerGroup, err := d.kafkaConsumerFactory.StartConsumerGroup(groupID, []string{topicName}, d.logger, handler)

	if err != nil {
		// we can not create a consumer - logging that, with reason
		d.logger.Info("Could not create proper consumer", zap.Error(err))
		return err
	}

	// sarama reports error in consumerGroup.Error() channel
	// this goroutine logs errors incoming
	go func() {
		for err = range consumerGroup.Errors() {
			panic(err)
		}
	}()

	d.channelSubscriptions[channelRef] = append(d.channelSubscriptions[channelRef], sub.UID)
	d.subscriptions[sub.UID] = sub
	d.subsConsumerGroups[sub.UID] = consumerGroup

	return nil
}

// unsubscribe reads kafkaConsumers which gets updated in UpdateConfig in a separate go-routine.
// unsubscribe must be called under updateLock.
func (d *KafkaDispatcher) unsubscribe(channel eventingchannels.ChannelReference, sub subscription) error {
	d.logger.Info("Unsubscribing from channel", zap.Any("channel", channel), zap.Any("subscription", sub))
	delete(d.subscriptions, sub.UID)
	if subsSlice, ok := d.channelSubscriptions[channel]; ok {
		var newSlice []types.UID
		for _, oldSub := range subsSlice {
			if oldSub != sub.UID {
				newSlice = append(newSlice, oldSub)
			}
		}
		d.channelSubscriptions[channel] = newSlice
	}
	if consumer, ok := d.subsConsumerGroups[sub.UID]; ok {
		delete(d.subsConsumerGroups, sub.UID)
		return consumer.Close()
	}
	return nil
}
func (d *KafkaDispatcher) getConfig() *multichannelfanout.Config {
	return d.config.Load().(*multichannelfanout.Config)
}

func (d *KafkaDispatcher) setConfig(config *multichannelfanout.Config) {
	d.config.Store(config)
}

func (d *KafkaDispatcher) getHostToChannelMap() map[string]eventingchannels.ChannelReference {
	return d.hostToChannelMap.Load().(map[string]eventingchannels.ChannelReference)
}

func (d *KafkaDispatcher) setHostToChannelMap(hcMap map[string]eventingchannels.ChannelReference) {
	d.hostToChannelMap.Store(hcMap)
}

func (d *KafkaDispatcher) getChannelReferenceFromHost(host string) (eventingchannels.ChannelReference, error) {
	chMap := d.getHostToChannelMap()
	cr, ok := chMap[host]
	if !ok {
		return cr, eventingchannels.UnknownHostError(host)
	}
	return cr, nil
}

func newSubscription(spec eventingduck.SubscriberSpec, name string, namespace string) subscription {
	return subscription{
		SubscriberSpec: spec,
		Name:           name,
		Namespace:      namespace,
	}
}
<commit_msg>Removed wrong panic (#1182)<commit_after>/*
Copyright 2018 The Knative 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 dispatcher

import (
	"context"
	"errors"
	"fmt"
	nethttp "net/http"
	"net/url"
	"sync"
	"sync/atomic"

	"github.com/Shopify/sarama"
	"github.com/cloudevents/sdk-go/v2/binding"
	protocolkafka "github.com/cloudevents/sdk-go/v2/protocol/kafka_sarama"
	"github.com/google/go-cmp/cmp"
	"go.uber.org/zap"
	"k8s.io/apimachinery/pkg/types"
	eventingduck "knative.dev/eventing/pkg/apis/duck/v1beta1"
	eventingchannels "knative.dev/eventing/pkg/channel"
	"knative.dev/eventing/pkg/channel/multichannelfanout"
	"knative.dev/eventing/pkg/kncloudevents"

	"knative.dev/eventing-contrib/kafka/channel/pkg/utils"
	"knative.dev/eventing-contrib/kafka/common/pkg/kafka"
)

type KafkaDispatcher struct {
	// TODO: config doesn't have to be atomic as it is read and updated using updateLock.
	config           atomic.Value
	hostToChannelMap atomic.Value
	// hostToChannelMapLock is used to update hostToChannelMap
	hostToChannelMapLock sync.Mutex

	messageSender *kncloudevents.HttpMessageSender
	receiver      *eventingchannels.MessageReceiver
	dispatcher    *eventingchannels.MessageDispatcherImpl

	kafkaAsyncProducer   sarama.AsyncProducer
	channelSubscriptions map[eventingchannels.ChannelReference][]types.UID
	subsConsumerGroups   map[types.UID]sarama.ConsumerGroup
	subscriptions        map[types.UID]subscription
	// consumerUpdateLock must be used to update kafkaConsumers
	consumerUpdateLock   sync.Mutex
	kafkaConsumerFactory kafka.KafkaConsumerGroupFactory

	topicFunc TopicFunc
	logger    *zap.Logger
}

func NewDispatcher(ctx context.Context, args *KafkaDispatcherArgs) (*KafkaDispatcher, error) {
	conf := sarama.NewConfig()
	conf.Version = sarama.V2_0_0_0
	conf.ClientID = args.ClientID
	conf.Consumer.Return.Errors = true // Returns the errors in ConsumerGroup#Errors() https://godoc.org/github.com/Shopify/sarama#ConsumerGroup
	client, err := sarama.NewClient(args.Brokers, conf)

	if err != nil {
		return nil, fmt.Errorf("unable to create kafka client: %v", err)
	}

	producer, err := sarama.NewAsyncProducerFromClient(client)
	if err != nil {
		return nil, fmt.Errorf("unable to create kafka producer: %v", err)
	}

	messageSender, err := kncloudevents.NewHttpMessageSender(args.KnCEConnectionArgs, "")
	if err != nil {
		args.Logger.Fatal("failed to create message sender", zap.Error(err))
	}

	dispatcher := &KafkaDispatcher{
		dispatcher:           eventingchannels.NewMessageDispatcher(args.Logger),
		kafkaConsumerFactory: kafka.NewConsumerGroupFactory(client),
		channelSubscriptions: make(map[eventingchannels.ChannelReference][]types.UID),
		subsConsumerGroups:   make(map[types.UID]sarama.ConsumerGroup),
		subscriptions:        make(map[types.UID]subscription),
		kafkaAsyncProducer:   producer,
		logger:               args.Logger,
		messageSender:        messageSender,
		topicFunc:            args.TopicFunc,
	}
	receiverFunc, err := eventingchannels.NewMessageReceiver(
		func(ctx context.Context, channel eventingchannels.ChannelReference, message binding.Message, transformers []binding.Transformer, _ nethttp.Header) error {
			kafkaProducerMessage := sarama.ProducerMessage{
				Topic: dispatcher.topicFunc(utils.KafkaChannelSeparator, channel.Namespace, channel.Name),
			}

			dispatcher.logger.Debug("Received a new message from MessageReceiver, dispatching to Kafka", zap.Any("channel", channel))
			err := protocolkafka.WriteProducerMessage(ctx, message, &kafkaProducerMessage, transformers...)
			if err != nil {
				return err
			}

			dispatcher.kafkaAsyncProducer.Input() <- &kafkaProducerMessage
			return nil
		},
		args.Logger,
		eventingchannels.ResolveMessageChannelFromHostHeader(dispatcher.getChannelReferenceFromHost))
	if err != nil {
		return nil, err
	}

	dispatcher.receiver = receiverFunc
	dispatcher.setConfig(&multichannelfanout.Config{})
	dispatcher.setHostToChannelMap(map[string]eventingchannels.ChannelReference{})
	return dispatcher, nil
}

type TopicFunc func(separator, namespace, name string) string

type KafkaDispatcherArgs struct {
	KnCEConnectionArgs *kncloudevents.ConnectionArgs
	ClientID           string
	Brokers            []string
	TopicFunc          TopicFunc
	Logger             *zap.Logger
}

type consumerMessageHandler struct {
	logger     *zap.Logger
	sub        subscription
	dispatcher *eventingchannels.MessageDispatcherImpl
}

func (c consumerMessageHandler) Handle(ctx context.Context, consumerMessage *sarama.ConsumerMessage) (bool, error) {
	defer func() {
		if r := recover(); r != nil {
			c.logger.Warn("Panic happened while handling a message",
				zap.String("topic", consumerMessage.Topic),
				zap.String("sub", string(c.sub.UID)),
				zap.Any("panic value", r),
			)
		}
	}()
	message := protocolkafka.NewMessageFromConsumerMessage(consumerMessage)
	if message.ReadEncoding() == binding.EncodingUnknown {
		return false, errors.New("received a message with unknown encoding")
	}
	var destination *url.URL
	if !c.sub.SubscriberURI.IsEmpty() {
		destination = c.sub.SubscriberURI.URL()
	}
	var reply *url.URL
	if !c.sub.ReplyURI.IsEmpty() {
		reply = c.sub.ReplyURI.URL()
	}
	var deadLetter *url.URL
	if c.sub.Delivery != nil && c.sub.Delivery.DeadLetterSink != nil && !c.sub.Delivery.DeadLetterSink.URI.IsEmpty() {
		deadLetter = c.sub.Delivery.DeadLetterSink.URI.URL()
	}
	c.logger.Debug("Going to dispatch the message",
		zap.String("topic", consumerMessage.Topic),
		zap.String("sub", string(c.sub.UID)),
	)
	err := c.dispatcher.DispatchMessage(context.Background(), message, nil, destination, reply, deadLetter)
	// NOTE: only return `true` here if DispatchMessage actually delivered the message.
	return err == nil, err
}

var _ kafka.KafkaConsumerHandler = (*consumerMessageHandler)(nil)

type subscription struct {
	eventingduck.SubscriberSpec
	Namespace string
	Name      string
}

// configDiff diffs the new config with the existing config. If there are no differences, then the
// empty string is returned. If there are differences, then a non-empty string is returned
// describing the differences.
func (d *KafkaDispatcher) configDiff(updated *multichannelfanout.Config) string {
	return cmp.Diff(d.getConfig(), updated)
}

// UpdateKafkaConsumers will be called by new CRD based kafka channel dispatcher controller.
func (d *KafkaDispatcher) UpdateKafkaConsumers(config *multichannelfanout.Config) (map[eventingduck.SubscriberSpec]error, error) {
	if config == nil {
		return nil, fmt.Errorf("nil config")
	}

	d.consumerUpdateLock.Lock()
	defer d.consumerUpdateLock.Unlock()

	var newSubs []types.UID
	failedToSubscribe := make(map[eventingduck.SubscriberSpec]error)
	for _, cc := range config.ChannelConfigs {
		channelRef := eventingchannels.ChannelReference{
			Name:      cc.Name,
			Namespace: cc.Namespace,
		}
		for _, subSpec := range cc.FanoutConfig.Subscriptions {
			sub := newSubscription(subSpec, string(subSpec.UID), cc.Namespace)
			newSubs = append(newSubs, sub.UID)

			// Check if sub already exists
			exists := false
			for _, s := range d.channelSubscriptions[channelRef] {
				if s == sub.UID {
					exists = true
				}
			}

			if !exists {
				// only subscribe when not exists in channel-subscriptions map
				// do not need to resubscribe every time channel fanout config is updated
				if err := d.subscribe(channelRef, sub); err != nil {
					failedToSubscribe[subSpec] = err
				}
			}
		}
	}

	d.logger.Debug("Number of new subs", zap.Any("subs", len(newSubs)))
	d.logger.Debug("Number of subs failed to subscribe", zap.Any("subs", len(failedToSubscribe)))

	// Unsubscribe and close consumer for any deleted subscriptions
	for channelRef, subs := range d.channelSubscriptions {
		for _, oldSub := range subs {
			removedSub := true
			for _, s := range newSubs {
				if s == oldSub {
					removedSub = false
				}
			}

			if removedSub {
				if err := d.unsubscribe(channelRef, d.subscriptions[oldSub]); err != nil {
					return nil, err
				}
			}
		}
		d.channelSubscriptions[channelRef] = newSubs
	}
	return failedToSubscribe, nil
}

// UpdateHostToChannelMap will be called by new CRD based kafka channel dispatcher controller.
func (d *KafkaDispatcher) UpdateHostToChannelMap(config *multichannelfanout.Config) error {
	if config == nil {
		return errors.New("nil config")
	}

	d.hostToChannelMapLock.Lock()
	defer d.hostToChannelMapLock.Unlock()

	hcMap, err := createHostToChannelMap(config)
	if err != nil {
		return err
	}

	d.setHostToChannelMap(hcMap)
	return nil
}

func createHostToChannelMap(config *multichannelfanout.Config) (map[string]eventingchannels.ChannelReference, error) {
	hcMap := make(map[string]eventingchannels.ChannelReference, len(config.ChannelConfigs))
	for _, cConfig := range config.ChannelConfigs {
		if cr, ok := hcMap[cConfig.HostName]; ok {
			return nil, fmt.Errorf(
				"duplicate hostName found. Each channel must have a unique host header. HostName:%s, channel:%s.%s, channel:%s.%s",
				cConfig.HostName,
				cConfig.Namespace,
				cConfig.Name,
				cr.Namespace,
				cr.Name)
		}
		hcMap[cConfig.HostName] = eventingchannels.ChannelReference{Name: cConfig.Name, Namespace: cConfig.Namespace}
	}
	return hcMap, nil
}

// Start starts the kafka dispatcher's message processing.
func (d *KafkaDispatcher) Start(ctx context.Context) error {
	if d.receiver == nil {
		return fmt.Errorf("message receiver is not set")
	}

	if d.kafkaAsyncProducer == nil {
		return fmt.Errorf("kafkaAsyncProducer is not set")
	}

	go func() {
		for {
			select {
			case e := <-d.kafkaAsyncProducer.Errors():
				d.logger.Warn("Got", zap.Error(e))
			case s := <-d.kafkaAsyncProducer.Successes():
				d.logger.Info("Sent", zap.Any("success", s))
			case <-ctx.Done():
				return
			}
		}
	}()

	return d.receiver.Start(ctx)
}

// subscribe reads kafkaConsumers which gets updated in UpdateConfig in a separate go-routine.
// subscribe must be called under updateLock.
func (d *KafkaDispatcher) subscribe(channelRef eventingchannels.ChannelReference, sub subscription) error {
	d.logger.Info("Subscribing", zap.Any("channelRef", channelRef), zap.Any("subscription", sub))

	topicName := d.topicFunc(utils.KafkaChannelSeparator, channelRef.Namespace, channelRef.Name)
	groupID := fmt.Sprintf("kafka.%s.%s.%s", sub.Namespace, channelRef.Name, sub.Name)

	handler := &consumerMessageHandler{d.logger, sub, d.dispatcher}

	consumerGroup, err := d.kafkaConsumerFactory.StartConsumerGroup(groupID, []string{topicName}, d.logger, handler)

	if err != nil {
		// we can not create a consumer - logging that, with reason
		d.logger.Info("Could not create proper consumer", zap.Error(err))
		return err
	}

	// sarama reports error in consumerGroup.Error() channel
	// this goroutine logs errors incoming
	go func() {
		for err = range consumerGroup.Errors() {
			d.logger.Warn("Error in consumer group", zap.Error(err))
		}
	}()

	d.channelSubscriptions[channelRef] = append(d.channelSubscriptions[channelRef], sub.UID)
	d.subscriptions[sub.UID] = sub
	d.subsConsumerGroups[sub.UID] = consumerGroup

	return nil
}

// unsubscribe reads kafkaConsumers which gets updated in UpdateConfig in a separate go-routine.
// unsubscribe must be called under updateLock.
func (d *KafkaDispatcher) unsubscribe(channel eventingchannels.ChannelReference, sub subscription) error {
	d.logger.Info("Unsubscribing from channel", zap.Any("channel", channel), zap.Any("subscription", sub))
	delete(d.subscriptions, sub.UID)
	if subsSlice, ok := d.channelSubscriptions[channel]; ok {
		var newSlice []types.UID
		for _, oldSub := range subsSlice {
			if oldSub != sub.UID {
				newSlice = append(newSlice, oldSub)
			}
		}
		d.channelSubscriptions[channel] = newSlice
	}
	if consumer, ok := d.subsConsumerGroups[sub.UID]; ok {
		delete(d.subsConsumerGroups, sub.UID)
		return consumer.Close()
	}
	return nil
}
func (d *KafkaDispatcher) getConfig() *multichannelfanout.Config {
	return d.config.Load().(*multichannelfanout.Config)
}

func (d *KafkaDispatcher) setConfig(config *multichannelfanout.Config) {
	d.config.Store(config)
}

func (d *KafkaDispatcher) getHostToChannelMap() map[string]eventingchannels.ChannelReference {
	return d.hostToChannelMap.Load().(map[string]eventingchannels.ChannelReference)
}

func (d *KafkaDispatcher) setHostToChannelMap(hcMap map[string]eventingchannels.ChannelReference) {
	d.hostToChannelMap.Store(hcMap)
}

func (d *KafkaDispatcher) getChannelReferenceFromHost(host string) (eventingchannels.ChannelReference, error) {
	chMap := d.getHostToChannelMap()
	cr, ok := chMap[host]
	if !ok {
		return cr, eventingchannels.UnknownHostError(host)
	}
	return cr, nil
}

func newSubscription(spec eventingduck.SubscriberSpec, name string, namespace string) subscription {
	return subscription{
		SubscriberSpec: spec,
		Name:           name,
		Namespace:      namespace,
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package main

import (
	"context"
	"net/http"
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"

	baz "github.com/uber/zanzibar/examples/example-gateway/build/clients/baz"
	clientsBazBaz "github.com/uber/zanzibar/examples/example-gateway/build/gen-code/clients/baz/baz"
	testBackend "github.com/uber/zanzibar/test/lib/test_backend"
)

const (
	httpPort     int32 = 8092
	tchannelPort int32 = 8094
)

func main() {
	var logger = zap.New(
		zapcore.NewCore(
			zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
			os.Stderr,
			zap.InfoLevel,
		),
	)

	httpBackend := serveHTTP(logger)
	_ = serverTChannel(logger)

	httpBackend.Wait()
}

func serveHTTP(logger *zap.Logger) *testBackend.TestHTTPBackend {
	httpBackend := testBackend.CreateHTTPBackend(httpPort)
	err := httpBackend.Bootstrap()
	if err != nil {
		panic(err)
	}
	handleContacts := func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(202)
		_, _ = w.Write([]byte("{}"))
	}
	handleGoogleNow := func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(202)
	}
	httpBackend.HandleFunc("POST", "/foo/contacts", handleContacts)
	httpBackend.HandleFunc("POST", "/add-credentials", handleGoogleNow)

	logger.Info("HTTP server listening on port & serving")

	return httpBackend
}

func serverTChannel(logger *zap.Logger) *testBackend.TestTChannelBackend {
	tchannelBackend, err := testBackend.CreateTChannelBackend(tchannelPort, "Qux")
	if err != nil {
		panic(err)
	}

	handleSimpleServiceCall := func(
		ctx context.Context,
		reqHeaders map[string]string,
		args *clientsBazBaz.SimpleService_Call_Args,
	) (map[string]string, error) {
		return nil, nil
	}
	simpleServiceCallHandler := baz.NewSimpleServiceCallHandler(handleSimpleServiceCall)

	// must register handler first before bootstrap
	tchannelBackend.Register("SimpleService", "Call", simpleServiceCallHandler)

	err = tchannelBackend.Bootstrap()
	if err != nil {
		panic(err)
	}

	logger.Info("TChannel server listening on port & serving")
	return tchannelBackend
}
<commit_msg>benchmarks: fixup method name call<commit_after>// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package main

import (
	"context"
	"net/http"
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"

	baz "github.com/uber/zanzibar/examples/example-gateway/build/clients/baz"
	clientsBazBaz "github.com/uber/zanzibar/examples/example-gateway/build/gen-code/clients/baz/baz"
	testBackend "github.com/uber/zanzibar/test/lib/test_backend"
)

const (
	httpPort     int32 = 8092
	tchannelPort int32 = 8094
)

func main() {
	var logger = zap.New(
		zapcore.NewCore(
			zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
			os.Stderr,
			zap.InfoLevel,
		),
	)

	httpBackend := serveHTTP(logger)
	_ = serverTChannel(logger)

	httpBackend.Wait()
}

func serveHTTP(logger *zap.Logger) *testBackend.TestHTTPBackend {
	httpBackend := testBackend.CreateHTTPBackend(httpPort)
	err := httpBackend.Bootstrap()
	if err != nil {
		panic(err)
	}
	handleContacts := func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(202)
		_, _ = w.Write([]byte("{}"))
	}
	handleGoogleNow := func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(202)
	}
	httpBackend.HandleFunc("POST", "/foo/contacts", handleContacts)
	httpBackend.HandleFunc("POST", "/add-credentials", handleGoogleNow)

	logger.Info("HTTP server listening on port & serving")

	return httpBackend
}

func serverTChannel(logger *zap.Logger) *testBackend.TestTChannelBackend {
	tchannelBackend, err := testBackend.CreateTChannelBackend(tchannelPort, "Qux")
	if err != nil {
		panic(err)
	}

	handleSimpleServiceCall := func(
		ctx context.Context,
		reqHeaders map[string]string,
		args *clientsBazBaz.SimpleService_Call_Args,
	) (map[string]string, error) {
		return nil, nil
	}
	simpleServiceCallHandler := baz.NewSimpleServiceCallHandler(handleSimpleServiceCall)

	// must register handler first before bootstrap
	tchannelBackend.Register("SimpleService", "call", simpleServiceCallHandler)

	err = tchannelBackend.Bootstrap()
	if err != nil {
		panic(err)
	}

	logger.Info("TChannel server listening on port & serving")
	return tchannelBackend
}
<|endoftext|>


<commit_before>package configure_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestConfigure(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Configure Suite")
}
<commit_msg>Increase the timeout kawasaki/configure tests<commit_after>package configure_test

import (
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestConfigure(t *testing.T) {
	SetDefaultEventuallyTimeout(2 * time.Second)
	RegisterFailHandler(Fail)
	RunSpecs(t, "Configure Suite")
}
<|endoftext|>


<commit_before>package main

import (
	"context"
	"crypto/tls"
	"log"

	nnet "github.com/nimona/go-nimona/net"
	prot "github.com/nimona/go-nimona/net/protocol"
)

func main() {
	peerA, err := newPeer("PeerA")
	if err != nil {
		log.Fatal("Could not create peer A", err)
	}

	peerB, err := newPeer("PeerB")
	if err != nil {
		log.Fatal("Could not create peer B", err)
	}

	peerC, err := newPeer("PeerC")
	if err != nil {
		log.Fatal("Could not create peer C", err)
	}

	log.Println("Peer A address:", peerA.GetAddresses())

	for _, addr := range peerA.GetAddresses() {
		endpoint := addr + "/tls/yamux/router/relay:keepalive"
		log.Println("-------- Dialing", endpoint)
		if _, _, err := peerB.DialContext(context.Background(), endpoint); err != nil {
			log.Println("Dial error", err)
		}

		// endpoint = addr + "/tls/yamux/router/ping"
		// time.Sleep(5 * time.Second)
		// log.Println("-------- SECOND Dial", endpoint)
		// if err := peerB.DialContext(context.Background(), endpoint); err != nil {
		// 	log.Println("Dial error", err)
		// }

		addrPeerB := peerB.GetAddresses()[0]
		endpoint = addrPeerB + "/tls/yamux/router/relay:" + addr + "/tls/yamux/router/ping"
		log.Println("-------- THIRD Dial", endpoint)
		if _, _, err := peerC.DialContext(context.Background(), endpoint); err != nil {
			log.Println("Dial error", err)
		}
	}
}

func newPeer(peerID string) (nnet.Net, error) {
	ctx := context.Background()
	crt, err := GenX509KeyPair()
	if err != nil {
		return nil, err
	}

	yamux := prot.NewYamux()
	router := prot.NewRouter()
	identity := &prot.IdentityProtocol{Local: peerID}
	tls := &prot.SecProtocol{
		Config: tls.Config{
			Certificates:       []tls.Certificate{crt},
			InsecureSkipVerify: true,
		},
	}
	ping := &Ping{}

	tcp := nnet.NewTransportTCP("0.0.0.0", 0)
	// ws := nnet.NewTransportWebsocket("0.0.0.0", 0)

	nn := nnet.New(ctx)
	relay := prot.NewRelayProtocol(nn)
	nn.AddTransport(yamux, router)
	nn.AddTransport(tcp, tls, yamux, router)
	// nn.AddTransport(ws, []nnet.Protocol{tls, yamux, router})
	nn.AddProtocols(router, tls, yamux, identity, ping, relay)
	router.AddRoute(relay)
	router.AddRoute(ping)
	router.AddRoute(identity, ping)
	return nn, nil
}
<commit_msg>Fix example<commit_after>package main

import (
	"context"
	"crypto/tls"
	"log"

	nnet "github.com/nimona/go-nimona/net"
	prot "github.com/nimona/go-nimona/net/protocol"
)

func main() {
	peerA, err := newPeer("PeerA")
	if err != nil {
		log.Fatal("Could not create peer A", err)
	}

	peerB, err := newPeer("PeerB")
	if err != nil {
		log.Fatal("Could not create peer B", err)
	}

	peerC, err := newPeer("PeerC")
	if err != nil {
		log.Fatal("Could not create peer C", err)
	}

	log.Println("Peer A address:", peerA.GetAddresses())

	for _, addr := range peerA.GetAddresses() {
		endpoint := addr + "/tls/yamux/router/relay:keepalive"
		log.Println("-------- Dialing", endpoint)
		if _, _, err := peerB.DialContext(context.Background(), endpoint); err != nil {
			log.Println("Dial error", err)
		}

		// endpoint = addr + "/tls/yamux/router/ping"
		// time.Sleep(5 * time.Second)
		// log.Println("-------- SECOND Dial", endpoint)
		// if err := peerB.DialContext(context.Background(), endpoint); err != nil {
		// 	log.Println("Dial error", err)
		// }

		addrPeerB := peerB.GetAddresses()[0]
		endpoint = addrPeerB + "/tls/yamux/router/relay:" + addr + "/tls/yamux/router/ping"
		log.Println("-------- THIRD Dial", endpoint)
		if _, _, err := peerC.DialContext(context.Background(), endpoint); err != nil {
			log.Println("Dial error", err)
		}
	}
}

func newPeer(peerID string) (nnet.Net, error) {
	ctx := context.Background()
	crt, err := GenX509KeyPair()
	if err != nil {
		return nil, err
	}

	yamux := prot.NewYamux()
	router := prot.NewRouter()
	identity := &prot.IdentityProtocol{Local: peerID}
	tls := &prot.SecProtocol{
		Config: tls.Config{
			Certificates:       []tls.Certificate{crt},
			InsecureSkipVerify: true,
		},
	}
	ping := &Ping{}

	tcp := nnet.NewTransportTCP("0.0.0.0", 0)
	// ws := nnet.NewTransportWebsocket("0.0.0.0", 0)

	nn := nnet.New(ctx)
	relay := prot.NewRelayProtocol(nn, []string{})
	nn.AddTransport(yamux, router)
	nn.AddTransport(tcp, tls, yamux, router)
	// nn.AddTransport(ws, []nnet.Protocol{tls, yamux, router})
	nn.AddProtocols(router, tls, yamux, identity, ping, relay)
	router.AddRoute(relay)
	router.AddRoute(ping)
	router.AddRoute(identity, ping)
	return nn, nil
}
<|endoftext|>


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

package main

const adapterTemplate = `// Code generated by adapter-generator. DO NOT EDIT.

package adapter

import (
	"fmt"
	"github.com/gogo/protobuf/proto"
	"github.com/ligato/cn-infra/datasync"
	. "github.com/ligato/cn-infra/kvscheduler/api"

    {{- range $i, $path := .Imports }}
	"{{ $path }}"
	{{- end }}
)

////////// type-safe key-value pair with metadata //////////

type {{ .DescriptorName }}KVWithMetadata struct {
	Key      string
	Value    {{ .ValueT }}
	Metadata {{ .MetadataT }}
	Origin   ValueOrigin
}

////////// type-safe Descriptor structure //////////

type {{ .DescriptorName }}Descriptor struct {
	Name               string
	KeySelector        KeySelector
	ValueTypeName      string
	KeyLabel           func(key string) string
	ValueComparator    func(key string, v1, v2 {{ .ValueT }}) bool
	NBKeyPrefix        []string
	WithMetadata       bool
	MetadataMapFactory MetadataMapFactory
	Add                func(key string, value {{ .ValueT }}) (metadata {{ .MetadataT }}, err error)
	Delete             func(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error
	Modify             func(key string, oldValue, newValue {{ .ValueT }}, oldMetadata {{ .MetadataT }}) (newMetadata {{ .MetadataT }}, err error)
	ModifyWithRecreate func(key string, oldValue, newValue {{ .ValueT }}, metadata {{ .MetadataT }}) bool
	Update             func(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error
	IsRetriableFailure func(err error) bool
	Dependencies       func(key string, value {{ .ValueT }}) []Dependency
	DerivedValues      func(key string, value {{ .ValueT }}) []KeyValuePair
	Dump               func(correlate []{{ .DescriptorName }}KVWithMetadata) ([]{{ .DescriptorName }}KVWithMetadata, error)
	DumpDependencies   []string /* descriptor name */
}

////////// Descriptor adapter //////////

type {{ .DescriptorName }}DescriptorAdapter struct {
	descriptor *{{ .DescriptorName }}Descriptor
}

func New{{ .DescriptorName }}Descriptor(typedDescriptor *{{ .DescriptorName }}Descriptor) *KVDescriptor {
	adapter := &{{ .DescriptorName }}DescriptorAdapter{descriptor: typedDescriptor}
	descriptor := &KVDescriptor{
		Name:               typedDescriptor.Name,
        KeySelector:        typedDescriptor.KeySelector,
        ValueTypeName:      typedDescriptor.ValueTypeName,
		KeyLabel:           typedDescriptor.KeyLabel,
		NBKeyPrefix:        typedDescriptor.NBKeyPrefix,
		WithMetadata:       typedDescriptor.WithMetadata,
        MetadataMapFactory: typedDescriptor.MetadataMapFactory,
		IsRetriableFailure: typedDescriptor.IsRetriableFailure,
		DumpDependencies:   typedDescriptor.DumpDependencies,
	}
	if typedDescriptor.ValueComparator != nil {
		descriptor.ValueComparator = adapter.ValueComparator
	}
	if typedDescriptor.Add != nil {
		descriptor.Add = adapter.Add
	}
	if typedDescriptor.Delete != nil {
		descriptor.Delete = adapter.Delete
	}
	if typedDescriptor.Modify != nil {
		descriptor.Modify = adapter.Modify
	}
	if typedDescriptor.ModifyWithRecreate != nil {
		descriptor.ModifyWithRecreate = adapter.ModifyWithRecreate
	}
	if typedDescriptor.Update != nil {
		descriptor.Update = adapter.Update
	}
	if typedDescriptor.Dependencies != nil {
		descriptor.Dependencies = adapter.Dependencies
	}
	if typedDescriptor.DerivedValues != nil {
		descriptor.DerivedValues = adapter.DerivedValues
	}
	if typedDescriptor.Dump != nil {
		descriptor.Dump = adapter.Dump
	}
	return descriptor
}

func (da *{{ .DescriptorName }}DescriptorAdapter) ValueComparator(key string, v1, v2 proto.Message) bool {
	typedV1, err1 := cast{{ .DescriptorName }}Value(key, v1)
	typedV2, err1 := cast{{ .DescriptorName }}Value(key, v2)
	if err1 != nil || err2 != nil {
		return false
	}
	return da.descriptor.ValueComparator(key, typedV1, typedV2)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Add(key string, value proto.Message) (metadata Metadata, err error) {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Add(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Modify(key string, oldValue, newValue proto.Message, oldMetadata Metadata) (newMetadata Metadata, err error) {
	oldTypedValue, err := cast{{ .DescriptorName }}Value(key, oldValue)
	if err != nil {
		return nil, err
	}
	newTypedValue, err := cast{{ .DescriptorName }}Value(key, newValue)
	if err != nil {
		return nil, err
	}
	typedOldMetadata, err := cast{{ .DescriptorName }}Metadata(key, oldMetadata)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Modify(key, oldTypedValue, newTypedValue, typedOldMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Delete(key string, value proto.Message, metadata Metadata) error {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return err
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return err
	}
	return da.descriptor.Delete(key, typedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) ModifyWithRecreate(key string, oldValue, newValue proto.Message, metadata Metadata) bool {
	oldTypedValue, err := cast{{ .DescriptorName }}Value(key, oldValue)
	if err != nil {
		return true
	}
	newTypedValue, err := cast{{ .DescriptorName }}Value(key, newValue)
	if err != nil {
		return true
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return true
	}
	return da.descriptor.ModifyWithRecreate(key, oldTypedValue, newTypedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Update(key string, value proto.Message, metadata Metadata) error {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return err
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return err
	}
	return da.descriptor.Update(key, typedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Dependencies(key string, value proto.Message) []Dependency {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil
	}
	return da.descriptor.Dependencies(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) DerivedValues(key string, value proto.Message) []KeyValuePair {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil
	}
	return da.descriptor.DerivedValues(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Dump(correlate []KVWithMetadata) ([]KVWithMetadata, error) {
	var correlateWithType []{{ .DescriptorName }}KVWithMetadata
	for _, kvpair := range correlate {
		typedValue, err := cast{{ .DescriptorName }}Value(kvpair.Key, kvpair.Value)
		if err != nil {
			continue
		}
		typedMetadata, err := cast{{ .DescriptorName }}Metadata(kvpair.Key, kvpair.Metadata)
		if err != nil {
			continue
		}
		correlateWithType = append(correlateWithType,
			{{ .DescriptorName }}KVWithMetadata{
				Key:      kvpair.Key,
				Value:    typedValue,
				Metadata: typedMetadata,
				Origin:   kvpair.Origin,
			})
	}

	typedDump, err := da.descriptor.Dump(correlateWithType)
	if err != nil {
		return nil, err
	}
	var dump []KVWithMetadata
	for _, typedKVWithMetadata := range typedDump {
		kvWithMetadata := KVWithMetadata{
			Key:      typedKVWithMetadata.Key,
			Metadata: typedKVWithMetadata.Metadata,
			Origin:   typedKVWithMetadata.Origin,
			}
		kvWithMetadata.Value = typedKVWithMetadata.Value
		dump = append(dump, kvWithMetadata)
	}
	return dump, err
}

////////// Helper methods //////////

func cast{{ .DescriptorName }}Value(key string, value Value) ({{ .ValueT }}, error) {
	typedValue, ok := value.({{ .ValueT }})
	if !ok {
		return nil, ErrInvalidValueType(key, value)
	}
	return typedValue, nil
}

func cast{{ .DescriptorName }}Metadata(key string, metadata Metadata) ({{ .MetadataT }}, error) {
	if metadata == nil {
		return nil, nil
	}
	typedMetadata, ok := metadata.({{ .MetadataT }})
	if !ok {
		return nil, ErrInvalidMetadataType(key)
	}
	return typedMetadata, nil
}
`
<commit_msg>Fix descriptor adapter template.<commit_after>// Copyright (c) 2018 Cisco and/or its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

const adapterTemplate = `// Code generated by adapter-generator. DO NOT EDIT.

package adapter

import (
	"fmt"
	"github.com/gogo/protobuf/proto"
	"github.com/ligato/cn-infra/datasync"
	. "github.com/ligato/cn-infra/kvscheduler/api"

    {{- range $i, $path := .Imports }}
	"{{ $path }}"
	{{- end }}
)

////////// type-safe key-value pair with metadata //////////

type {{ .DescriptorName }}KVWithMetadata struct {
	Key      string
	Value    {{ .ValueT }}
	Metadata {{ .MetadataT }}
	Origin   ValueOrigin
}

////////// type-safe Descriptor structure //////////

type {{ .DescriptorName }}Descriptor struct {
	Name               string
	KeySelector        KeySelector
	ValueTypeName      string
	KeyLabel           func(key string) string
	ValueComparator    func(key string, v1, v2 {{ .ValueT }}) bool
	NBKeyPrefix        string
	WithMetadata       bool
	MetadataMapFactory MetadataMapFactory
	Add                func(key string, value {{ .ValueT }}) (metadata {{ .MetadataT }}, err error)
	Delete             func(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error
	Modify             func(key string, oldValue, newValue {{ .ValueT }}, oldMetadata {{ .MetadataT }}) (newMetadata {{ .MetadataT }}, err error)
	ModifyWithRecreate func(key string, oldValue, newValue {{ .ValueT }}, metadata {{ .MetadataT }}) bool
	Update             func(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error
	IsRetriableFailure func(err error) bool
	Dependencies       func(key string, value {{ .ValueT }}) []Dependency
	DerivedValues      func(key string, value {{ .ValueT }}) []KeyValuePair
	Dump               func(correlate []{{ .DescriptorName }}KVWithMetadata) ([]{{ .DescriptorName }}KVWithMetadata, error)
	DumpDependencies   []string /* descriptor name */
}

////////// Descriptor adapter //////////

type {{ .DescriptorName }}DescriptorAdapter struct {
	descriptor *{{ .DescriptorName }}Descriptor
}

func New{{ .DescriptorName }}Descriptor(typedDescriptor *{{ .DescriptorName }}Descriptor) *KVDescriptor {
	adapter := &{{ .DescriptorName }}DescriptorAdapter{descriptor: typedDescriptor}
	descriptor := &KVDescriptor{
		Name:               typedDescriptor.Name,
        KeySelector:        typedDescriptor.KeySelector,
        ValueTypeName:      typedDescriptor.ValueTypeName,
		KeyLabel:           typedDescriptor.KeyLabel,
		NBKeyPrefix:        typedDescriptor.NBKeyPrefix,
		WithMetadata:       typedDescriptor.WithMetadata,
        MetadataMapFactory: typedDescriptor.MetadataMapFactory,
		IsRetriableFailure: typedDescriptor.IsRetriableFailure,
		DumpDependencies:   typedDescriptor.DumpDependencies,
	}
	if typedDescriptor.ValueComparator != nil {
		descriptor.ValueComparator = adapter.ValueComparator
	}
	if typedDescriptor.Add != nil {
		descriptor.Add = adapter.Add
	}
	if typedDescriptor.Delete != nil {
		descriptor.Delete = adapter.Delete
	}
	if typedDescriptor.Modify != nil {
		descriptor.Modify = adapter.Modify
	}
	if typedDescriptor.ModifyWithRecreate != nil {
		descriptor.ModifyWithRecreate = adapter.ModifyWithRecreate
	}
	if typedDescriptor.Update != nil {
		descriptor.Update = adapter.Update
	}
	if typedDescriptor.Dependencies != nil {
		descriptor.Dependencies = adapter.Dependencies
	}
	if typedDescriptor.DerivedValues != nil {
		descriptor.DerivedValues = adapter.DerivedValues
	}
	if typedDescriptor.Dump != nil {
		descriptor.Dump = adapter.Dump
	}
	return descriptor
}

func (da *{{ .DescriptorName }}DescriptorAdapter) ValueComparator(key string, v1, v2 proto.Message) bool {
	typedV1, err1 := cast{{ .DescriptorName }}Value(key, v1)
	typedV2, err1 := cast{{ .DescriptorName }}Value(key, v2)
	if err1 != nil || err2 != nil {
		return false
	}
	return da.descriptor.ValueComparator(key, typedV1, typedV2)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Add(key string, value proto.Message) (metadata Metadata, err error) {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Add(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Modify(key string, oldValue, newValue proto.Message, oldMetadata Metadata) (newMetadata Metadata, err error) {
	oldTypedValue, err := cast{{ .DescriptorName }}Value(key, oldValue)
	if err != nil {
		return nil, err
	}
	newTypedValue, err := cast{{ .DescriptorName }}Value(key, newValue)
	if err != nil {
		return nil, err
	}
	typedOldMetadata, err := cast{{ .DescriptorName }}Metadata(key, oldMetadata)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Modify(key, oldTypedValue, newTypedValue, typedOldMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Delete(key string, value proto.Message, metadata Metadata) error {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return err
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return err
	}
	return da.descriptor.Delete(key, typedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) ModifyWithRecreate(key string, oldValue, newValue proto.Message, metadata Metadata) bool {
	oldTypedValue, err := cast{{ .DescriptorName }}Value(key, oldValue)
	if err != nil {
		return true
	}
	newTypedValue, err := cast{{ .DescriptorName }}Value(key, newValue)
	if err != nil {
		return true
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return true
	}
	return da.descriptor.ModifyWithRecreate(key, oldTypedValue, newTypedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Update(key string, value proto.Message, metadata Metadata) error {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return err
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return err
	}
	return da.descriptor.Update(key, typedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Dependencies(key string, value proto.Message) []Dependency {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil
	}
	return da.descriptor.Dependencies(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) DerivedValues(key string, value proto.Message) []KeyValuePair {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil
	}
	return da.descriptor.DerivedValues(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Dump(correlate []KVWithMetadata) ([]KVWithMetadata, error) {
	var correlateWithType []{{ .DescriptorName }}KVWithMetadata
	for _, kvpair := range correlate {
		typedValue, err := cast{{ .DescriptorName }}Value(kvpair.Key, kvpair.Value)
		if err != nil {
			continue
		}
		typedMetadata, err := cast{{ .DescriptorName }}Metadata(kvpair.Key, kvpair.Metadata)
		if err != nil {
			continue
		}
		correlateWithType = append(correlateWithType,
			{{ .DescriptorName }}KVWithMetadata{
				Key:      kvpair.Key,
				Value:    typedValue,
				Metadata: typedMetadata,
				Origin:   kvpair.Origin,
			})
	}

	typedDump, err := da.descriptor.Dump(correlateWithType)
	if err != nil {
		return nil, err
	}
	var dump []KVWithMetadata
	for _, typedKVWithMetadata := range typedDump {
		kvWithMetadata := KVWithMetadata{
			Key:      typedKVWithMetadata.Key,
			Metadata: typedKVWithMetadata.Metadata,
			Origin:   typedKVWithMetadata.Origin,
			}
		kvWithMetadata.Value = typedKVWithMetadata.Value
		dump = append(dump, kvWithMetadata)
	}
	return dump, err
}

////////// Helper methods //////////

func cast{{ .DescriptorName }}Value(key string, value proto.Message) ({{ .ValueT }}, error) {
	typedValue, ok := value.({{ .ValueT }})
	if !ok {
		return nil, ErrInvalidValueType(key, value)
	}
	return typedValue, nil
}

func cast{{ .DescriptorName }}Metadata(key string, metadata Metadata) ({{ .MetadataT }}, error) {
	if metadata == nil {
		return nil, nil
	}
	typedMetadata, ok := metadata.({{ .MetadataT }})
	if !ok {
		return nil, ErrInvalidMetadataType(key)
	}
	return typedMetadata, nil
}
`
<|endoftext|>


<commit_before>package nodos

import (
	"fmt"
	"os"

	"golang.org/x/sys/windows"

	"github.com/Microsoft/go-winio"
)

func CreateJunction(target, mountPt string) error {
	_mountPt, err := windows.UTF16PtrFromString(mountPt)
	if err != nil {
		return fmt.Errorf("%s: %s", mountPt, err)
	}

	err = os.Mkdir(mountPt, 0777)
	if err != nil {
		return fmt.Errorf("%s: %s", mountPt, err)
	}
	ok := false
	defer func() {
		if !ok {
			os.Remove(mountPt)
		}
	}()

	handle, err := windows.CreateFile(_mountPt,
		windows.GENERIC_WRITE,
		0,
		nil,
		windows.OPEN_EXISTING,
		windows.FILE_FLAG_BACKUP_SEMANTICS,
		0)
	if err != nil {
		return fmt.Errorf("%s: %s", mountPt, err)
	}
	defer windows.CloseHandle(handle)

	rp := winio.ReparsePoint{
		Target:       target,
		IsMountPoint: true,
	}

	data := winio.EncodeReparsePoint(&rp)

	var size uint32

	err = windows.DeviceIoControl(
		handle,
		FSCTL_SET_REPARSE_POINT,
		&data[0],
		uint32(len(data)),
		nil,
		0,
		&size,
		nil)

	if err != nil {
		return fmt.Errorf("windows.DeviceIoControl: %s", err)
	}
	ok = true
	return nil
}
<commit_msg>Fix: `mklink /J mountPt target-relative-path` made a broken junction.<commit_after>package nodos

import (
	"fmt"
	"os"
	"path/filepath"

	"golang.org/x/sys/windows"

	"github.com/Microsoft/go-winio"
)

func CreateJunction(target, mountPt string) error {
	_target, err := filepath.Abs(target)
	if err != nil {
		return fmt.Errorf("%s: %s", target, err)
	}
	_mountPt, err := windows.UTF16PtrFromString(mountPt)
	if err != nil {
		return fmt.Errorf("%s: %s", mountPt, err)
	}

	err = os.Mkdir(mountPt, 0777)
	if err != nil {
		return fmt.Errorf("%s: %s", mountPt, err)
	}
	ok := false
	defer func() {
		if !ok {
			os.Remove(mountPt)
		}
	}()

	handle, err := windows.CreateFile(_mountPt,
		windows.GENERIC_WRITE,
		0,
		nil,
		windows.OPEN_EXISTING,
		windows.FILE_FLAG_BACKUP_SEMANTICS,
		0)
	if err != nil {
		return fmt.Errorf("%s: %s", mountPt, err)
	}
	defer windows.CloseHandle(handle)

	rp := winio.ReparsePoint{
		Target:       _target,
		IsMountPoint: true,
	}

	data := winio.EncodeReparsePoint(&rp)

	var size uint32

	err = windows.DeviceIoControl(
		handle,
		FSCTL_SET_REPARSE_POINT,
		&data[0],
		uint32(len(data)),
		nil,
		0,
		&size,
		nil)

	if err != nil {
		return fmt.Errorf("windows.DeviceIoControl: %s", err)
	}
	ok = true
	return nil
}
<|endoftext|>


<commit_before>package configuration

import (
	"encoding/json"
	"fmt"

	"github.com/bborbe/monitoring/check/http"
	"github.com/bborbe/monitoring/check/tcp"
	"github.com/bborbe/monitoring/node"
)

type Configuration interface {
	Nodes() []node.Node
}

type configuration struct {
}

func New() Configuration {
	return new(configuration)
}

func (c *configuration) Nodes() []node.Node {
	list := make([]node.Node, 0)
	list = append(list, createNodeInternetAvaiable())
	return list
}

func createNodeInternetAvaiable() node.Node {
	return node.New(tcp.New("www.google.com", 80), createExternalNode(), createHmNode(), createRnNode(), createRaspVPN(), createRocketnewsVPN()).Silent(true)
}

func createExternalNode() node.Node {
	return node.New(http.New("http://benjaminborbe.zenfolio.com/").ExpectTitle("Zenfolio | Benjamin Borbe Fotografie"))
}

func createRnNode() node.Node {
	list := make([]node.Node, 0)

	list = append(list, node.New(tcp.New("144.76.187.199", 22)))
	list = append(list, node.New(tcp.New("144.76.187.200", 22)))
	list = append(list, node.New(tcp.New("144.76.187.199", 80)))
	list = append(list, node.New(tcp.New("144.76.187.200", 80)))
	list = append(list, node.New(tcp.New("144.76.187.199", 443)))
	list = append(list, node.New(tcp.New("144.76.187.200", 443)))

	list = append(list, node.New(http.New("http://www.benjamin-borbe.de/").ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/").ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("http://www.benjaminborbe.de/").ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("https://www.benjaminborbe.de/").ExpectTitle("Portfolio")))

	list = append(list, node.New(http.New("http://www.benjamin-borbe.de/blog").ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/blog").ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("http://www.benjaminborbe.de/blog").ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("https://www.benjaminborbe.de/blog").ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("http://www.benjamin-borbe.de/blog/").ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/blog/").ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("http://www.benjaminborbe.de/blog/").ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("https://www.benjaminborbe.de/blog/").ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("http://blog.benjamin-borbe.de/").ExpectTitle("Benjamin Borbe Fotografie")))

	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/googlebd5f3e34a3e508a2.html").ExpectContent("google-site-verification: googlebd5f3e34a3e508a2.html")))
	list = append(list, node.New(http.New("https://www.harteslicht.de/googlebd5f3e34a3e508a2.html").ExpectContent("google-site-verification: googlebd5f3e34a3e508a2.html")))
	list = append(list, node.New(http.New("https://www.harteslicht.com/googlebd5f3e34a3e508a2.html").ExpectContent("google-site-verification: googlebd5f3e34a3e508a2.html")))

	list = append(list, node.New(http.New("http://www.harteslicht.com/").ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("http://www.harteslicht.de/").ExpectTitle("Portfolio")))

	list = append(list, node.New(http.New("http://www.harteslicht.com/blog/").ExpectTitle("www.Harteslicht.com | Fotografieren das Spass macht.")))
	list = append(list, node.New(http.New("http://www.harteslicht.de/blog/").ExpectTitle("www.Harteslicht.com | Fotografieren das Spass macht.")))
	list = append(list, node.New(http.New("http://blog.harteslicht.com/").ExpectTitle("www.Harteslicht.com | Fotografieren das Spass macht.")))
	list = append(list, node.New(http.New("http://blog.harteslicht.de/").ExpectTitle("www.Harteslicht.com | Fotografieren das Spass macht.")))

	list = append(list, node.New(http.New("http://portfolio.benjamin-borbe.de/")))
	list = append(list, node.New(http.New("http://jana-und-ben.benjamin-borbe.de/").ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("http://jbf.benjamin-borbe.de/").ExpectTitle("Portfolio")))

	list = append(list, node.New(http.New("http://confluence.benjamin-borbe.de/").ExpectTitle("Dashboard - Confluence")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/confluence").ExpectTitle("Dashboard - Confluence")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/confluence/").ExpectTitle("Dashboard - Confluence")))

	list = append(list, node.New(http.New("http://portfolio.harteslicht.com/")))
	list = append(list, node.New(http.New("http://portfolio.harteslicht.de/")))

	list = append(list, node.New(http.New("http://kickstart.benjamin-borbe.de/").ExpectBody("ks.cfg")))
	list = append(list, node.New(http.New("http://ks.benjamin-borbe.de/").ExpectBody("ks.cfg")))

	list = append(list, node.New(http.New("http://slideshow.benjamin-borbe.de/").ExpectBody("go.html")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/slideshow/").ExpectBody("go.html")))

	list = append(list, node.New(http.New("http://jenkins.benjamin-borbe.de/").ExpectTitle("Dashboard [Jenkins]")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/jenkins").ExpectTitle("Dashboard [Jenkins]")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/jenkins/").ExpectTitle("Dashboard [Jenkins]")))

	list = append(list, node.New(http.New("http://ip.benjamin-borbe.de/")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/ip")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/ip/")))

	list = append(list, node.New(http.New("http://rocketnews.de/")))
	list = append(list, node.New(http.New("http://www.rocketnews.de/")))
	list = append(list, node.New(http.New("http://rocketsource.de/")))
	list = append(list, node.New(http.New("http://www.rocketsource.de/")))

	list = append(list, node.New(http.New("http://backup.benjamin-borbe.de/").ExpectBody("Backup-Status")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/backup").ExpectBody("Backup-Status")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/backup/").ExpectBody("Backup-Status")))

	list = append(list, node.New(http.New("http://booking.benjamin-borbe.de/status").ExpectContent("OK")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/booking/status").ExpectContent("OK")))

	list = append(list, node.New(http.New("http://aptly.benjamin-borbe.de/").ExpectTitle(`Index of /`)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/aptly").ExpectTitle(`Index of /`)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/aptly/").ExpectTitle(`Index of /`)))
	list = append(list, node.New(http.New("http://aptly.benjamin-borbe.de/api/version").AuthFile("api", "/etc/aptly_api_password").ExpectContent(`{"Version":"0.9.5"}`)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/aptly/api/version").AuthFile("api", "/etc/aptly_api_password").ExpectContent(`{"Version":"0.9.5"}`)))

	list = append(list, createRnMailNode())

	return node.New(tcp.New("host.rocketsource.de", 22), list...)
}

func createRnMailNode() node.Node {
	list := make([]node.Node, 0)
	list = append(list, node.New(tcp.New("iredmail.mailfolder.org", 143)))
	list = append(list, node.New(tcp.New("iredmail.mailfolder.org", 993)))
	list = append(list, node.New(tcp.New("iredmail.mailfolder.org", 465)))
	return node.New(tcp.New("iredmail.mailfolder.org", 22), list...)
}

func createPnNode() node.Node {
	list := make([]node.Node, 0)
	var contentExpectation http.Expectation
	contentExpectation = checkBackupJson
	list = append(list, node.New(http.New("http://backup.pn.benjamin-borbe.de:7777?status=false").AddExpectation(contentExpectation)))
	return node.New(tcp.New("backup.pn.benjamin-borbe.de", 7777), list...)
}

func createRaspVPN() node.Node {
	return node.New(tcp.New("10.30.0.1", 22), createPnNode()).Silent(true)
}

func createRocketnewsVPN() node.Node {
	return node.New(tcp.New("10.20.0.1", 22)).Silent(true)
}

func createHmNode() node.Node {
	list := make([]node.Node, 0)
	return node.New(tcp.New("home.benjamin-borbe.de", 443), list...)
}

func checkBackupJson(resp *http.HttpResponse) error {
	var data []interface{}
	err := json.Unmarshal(resp.Content, &data)
	if err != nil {
		return fmt.Errorf("parse json failed")
	}
	if len(data) > 0 {
		return fmt.Errorf("found false backups")
	}
	return nil
}
<commit_msg>add statuscode check and password.bb nodes<commit_after>package configuration

import (
	"encoding/json"
	"fmt"

	"github.com/bborbe/monitoring/check/http"
	"github.com/bborbe/monitoring/check/tcp"
	"github.com/bborbe/monitoring/node"
)

type Configuration interface {
	Nodes() []node.Node
}

type configuration struct {
}

func New() Configuration {
	return new(configuration)
}

func (c *configuration) Nodes() []node.Node {
	list := make([]node.Node, 0)
	list = append(list, createNodeInternetAvaiable())
	return list
}

func createNodeInternetAvaiable() node.Node {
	return node.New(tcp.New("www.google.com", 80), createExternalNode(), createHmNode(), createRnNode(), createRaspVPN(), createRocketnewsVPN()).Silent(true)
}

func createExternalNode() node.Node {
	return node.New(http.New("http://benjaminborbe.zenfolio.com/").ExpectStatusCode(200).ExpectTitle("Zenfolio | Benjamin Borbe Fotografie"))
}

func createRnNode() node.Node {
	list := make([]node.Node, 0)

	list = append(list, node.New(tcp.New("144.76.187.199", 22)))
	list = append(list, node.New(tcp.New("144.76.187.200", 22)))
	list = append(list, node.New(tcp.New("144.76.187.199", 80)))
	list = append(list, node.New(tcp.New("144.76.187.200", 80)))
	list = append(list, node.New(tcp.New("144.76.187.199", 443)))
	list = append(list, node.New(tcp.New("144.76.187.200", 443)))

	list = append(list, node.New(http.New("http://www.benjamin-borbe.de/").ExpectStatusCode(200).ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/").ExpectStatusCode(200).ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("http://www.benjaminborbe.de/").ExpectStatusCode(200).ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("https://www.benjaminborbe.de/").ExpectStatusCode(200).ExpectTitle("Portfolio")))

	list = append(list, node.New(http.New("http://www.benjamin-borbe.de/blog").ExpectStatusCode(200).ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/blog").ExpectStatusCode(200).ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("http://www.benjaminborbe.de/blog").ExpectStatusCode(200).ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("https://www.benjaminborbe.de/blog").ExpectStatusCode(200).ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("http://www.benjamin-borbe.de/blog/").ExpectStatusCode(200).ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/blog/").ExpectStatusCode(200).ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("http://www.benjaminborbe.de/blog/").ExpectStatusCode(200).ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("https://www.benjaminborbe.de/blog/").ExpectStatusCode(200).ExpectTitle("Benjamin Borbe Fotografie")))
	list = append(list, node.New(http.New("http://blog.benjamin-borbe.de/").ExpectStatusCode(200).ExpectTitle("Benjamin Borbe Fotografie")))

	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/googlebd5f3e34a3e508a2.html").ExpectStatusCode(200).ExpectContent("google-site-verification: googlebd5f3e34a3e508a2.html")))
	list = append(list, node.New(http.New("https://www.harteslicht.de/googlebd5f3e34a3e508a2.html").ExpectStatusCode(200).ExpectContent("google-site-verification: googlebd5f3e34a3e508a2.html")))
	list = append(list, node.New(http.New("https://www.harteslicht.com/googlebd5f3e34a3e508a2.html").ExpectStatusCode(200).ExpectContent("google-site-verification: googlebd5f3e34a3e508a2.html")))

	list = append(list, node.New(http.New("http://www.harteslicht.com/").ExpectStatusCode(200).ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("http://www.harteslicht.de/").ExpectStatusCode(200).ExpectTitle("Portfolio")))

	list = append(list, node.New(http.New("http://www.harteslicht.com/blog/").ExpectStatusCode(200).ExpectTitle("www.Harteslicht.com | Fotografieren das Spass macht.")))
	list = append(list, node.New(http.New("http://www.harteslicht.de/blog/").ExpectStatusCode(200).ExpectTitle("www.Harteslicht.com | Fotografieren das Spass macht.")))
	list = append(list, node.New(http.New("http://blog.harteslicht.com/").ExpectStatusCode(200).ExpectTitle("www.Harteslicht.com | Fotografieren das Spass macht.")))
	list = append(list, node.New(http.New("http://blog.harteslicht.de/").ExpectStatusCode(200).ExpectTitle("www.Harteslicht.com | Fotografieren das Spass macht.")))

	list = append(list, node.New(http.New("http://portfolio.benjamin-borbe.de/")))
	list = append(list, node.New(http.New("http://jana-und-ben.benjamin-borbe.de/").ExpectStatusCode(200).ExpectTitle("Portfolio")))
	list = append(list, node.New(http.New("http://jbf.benjamin-borbe.de/").ExpectStatusCode(200).ExpectTitle("Portfolio")))

	list = append(list, node.New(http.New("http://confluence.benjamin-borbe.de/").ExpectStatusCode(200).ExpectTitle("Dashboard - Confluence")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/confluence").ExpectStatusCode(200).ExpectTitle("Dashboard - Confluence")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/confluence/").ExpectStatusCode(200).ExpectTitle("Dashboard - Confluence")))

	list = append(list, node.New(http.New("http://portfolio.harteslicht.com/").ExpectStatusCode(200)))
	list = append(list, node.New(http.New("http://portfolio.harteslicht.de/").ExpectStatusCode(200)))

	list = append(list, node.New(http.New("http://kickstart.benjamin-borbe.de/").ExpectStatusCode(200).ExpectBody("ks.cfg")))
	list = append(list, node.New(http.New("http://ks.benjamin-borbe.de/").ExpectStatusCode(200).ExpectBody("ks.cfg")))

	list = append(list, node.New(http.New("http://slideshow.benjamin-borbe.de/").ExpectStatusCode(200).ExpectBody("go.html")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/slideshow/").ExpectStatusCode(200).ExpectBody("go.html")))

	list = append(list, node.New(http.New("http://jenkins.benjamin-borbe.de/").ExpectStatusCode(200).ExpectTitle("Dashboard [Jenkins]")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/jenkins").ExpectStatusCode(200).ExpectTitle("Dashboard [Jenkins]")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/jenkins/").ExpectStatusCode(200).ExpectTitle("Dashboard [Jenkins]")))

	list = append(list, node.New(http.New("http://ip.benjamin-borbe.de/").ExpectStatusCode(200)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/ip").ExpectStatusCode(200)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/ip/").ExpectStatusCode(200)))

	list = append(list, node.New(http.New("http://password.benjamin-borbe.de/").ExpectStatusCode(200)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/password").ExpectStatusCode(200)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/password/").ExpectStatusCode(200)))

	list = append(list, node.New(http.New("http://rocketnews.de/").ExpectStatusCode(200)))
	list = append(list, node.New(http.New("http://www.rocketnews.de/").ExpectStatusCode(200)))
	list = append(list, node.New(http.New("http://rocketsource.de/").ExpectStatusCode(200)))
	list = append(list, node.New(http.New("http://www.rocketsource.de/").ExpectStatusCode(200)))

	list = append(list, node.New(http.New("http://backup.benjamin-borbe.de/").ExpectStatusCode(200).ExpectBody("Backup-Status")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/backup").ExpectStatusCode(200).ExpectBody("Backup-Status")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/backup/").ExpectStatusCode(200).ExpectBody("Backup-Status")))

	list = append(list, node.New(http.New("http://booking.benjamin-borbe.de/status").ExpectStatusCode(200).ExpectStatusCode(200).ExpectContent("OK")))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/booking/status").ExpectStatusCode(200).ExpectStatusCode(200).ExpectContent("OK")))

	list = append(list, node.New(http.New("http://aptly.benjamin-borbe.de/").ExpectStatusCode(200).ExpectTitle(`Index of /`)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/aptly").ExpectStatusCode(200).ExpectTitle(`Index of /`)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/aptly/").ExpectStatusCode(200).ExpectTitle(`Index of /`)))
	list = append(list, node.New(http.New("http://aptly.benjamin-borbe.de/api/version").ExpectStatusCode(200).AuthFile("api", "/etc/aptly_api_password").ExpectContent(`{"Version":"0.9.5"}`)))
	list = append(list, node.New(http.New("https://www.benjamin-borbe.de/aptly/api/version").ExpectStatusCode(200).AuthFile("api", "/etc/aptly_api_password").ExpectContent(`{"Version":"0.9.5"}`)))

	list = append(list, createRnMailNode())

	return node.New(tcp.New("host.rocketsource.de", 22), list...)
}

func createRnMailNode() node.Node {
	list := make([]node.Node, 0)
	list = append(list, node.New(tcp.New("iredmail.mailfolder.org", 143)))
	list = append(list, node.New(tcp.New("iredmail.mailfolder.org", 993)))
	list = append(list, node.New(tcp.New("iredmail.mailfolder.org", 465)))
	return node.New(tcp.New("iredmail.mailfolder.org", 22), list...)
}

func createPnNode() node.Node {
	list := make([]node.Node, 0)
	var contentExpectation http.Expectation
	contentExpectation = checkBackupJson
	list = append(list, node.New(http.New("http://backup.pn.benjamin-borbe.de:7777?status=false").ExpectStatusCode(200).AddExpectation(contentExpectation)))
	return node.New(tcp.New("backup.pn.benjamin-borbe.de", 7777), list...)
}

func createRaspVPN() node.Node {
	return node.New(tcp.New("10.30.0.1", 22), createPnNode()).Silent(true)
}

func createRocketnewsVPN() node.Node {
	return node.New(tcp.New("10.20.0.1", 22)).Silent(true)
}

func createHmNode() node.Node {
	list := make([]node.Node, 0)
	return node.New(tcp.New("home.benjamin-borbe.de", 443), list...)
}

func checkBackupJson(resp *http.HttpResponse) error {
	var data []interface{}
	err := json.Unmarshal(resp.Content, &data)
	if err != nil {
		return fmt.Errorf("parse json failed")
	}
	if len(data) > 0 {
		return fmt.Errorf("found false backups")
	}
	return nil
}
<|endoftext|>