<commit_before>package bidirpc

import (
	"fmt"
	"io"
	"log"
	"net"
	"sync"
	"sync/atomic"
	"testing"
)

type Args struct {
	Name string
}

type Reply struct {
	Msg string
}

type Service struct {
	name      string
	callCount int32
}

func (s *Service) SayHi(args Args, reply *Reply) error {
	reply.Msg = fmt.Sprintf("[%v] Hi %v, from %v", atomic.LoadInt32(&s.callCount), args.Name, s.name)
	atomic.AddInt32(&s.callCount, 1)
	return nil
}

func TestBasic(t *testing.T) {
	connYin, connYang := net.Pipe()

	registryYin := NewRegistry()
	registryYang := NewRegistry()

	serviceYin := &Service{name: "Yin"}
	err := registryYin.Register(serviceYin)
	if err != nil {
		t.Fatalf("Register error: %v", err)
	}

	serviceYang := &Service{name: "Yang"}
	err = registryYang.Register(serviceYang)
	if err != nil {
		t.Fatalf("Register error: %v", err)
	}

	sessionYin, err := NewSession(connYin, Yin, registryYin, 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}
	sessionYang, err := NewSession(connYang, Yang, registryYang, 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(2)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatal("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()
	go func() {
		if err := sessionYang.Serve(); err != nil {
			t.Fatal("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	for i := 0; i < 3; i++ {
		args := Args{"Windows"}
		reply := new(Reply)
		err = sessionYin.Call("Service.SayHi", args, reply)
		if err != nil {
			t.Fatalf("Call error: %v", err)
		}
		t.Logf("reply = %v\n", reply.Msg)

		args.Name = "OSX"
		err = sessionYang.Call("Service.SayHi", args, reply)
		if err != nil {
			t.Fatalf("Call error: %v", err)
		}
		t.Logf("reply = %v\n", reply.Msg)

		args.Name = "iOS"
		err = sessionYin.Call("Service.SayHi", args, reply)
		if err != nil {
			t.Fatalf("Call error: %v", err)
		}
		t.Logf("reply = %v\n", reply.Msg)
	}

	err = registryYang.RegisterName("NewService", serviceYang)
	if err != nil {
		t.Fatalf("RegisterName error: %v", err)
	}
	args := Args{"Linux"}
	reply := new(Reply)
	call := sessionYin.Go("NewService.SayHi", args, reply, nil)
	<-call.Done
	if call.Error != nil {
		t.Fatalf("Go error: %v", call.Error)
	}
	t.Logf("reply = %v\n", reply.Msg)

	sessionYin.Close()
	sessionYang.Close()
	sessionWait.Wait()
}

func TestReadError(t *testing.T) {
	connYin, connYang := net.Pipe()
	connYang.Close()

	sessionYin, err := NewSession(connYin, Yin, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatal("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYin.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYin.Close()
	sessionWait.Wait()
}

func TestWriteError(t *testing.T) {
	connYin, _ := net.Pipe()
	connYin.Close()

	sessionYin, err := NewSession(connYin, Yin, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatal("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYin.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYin.Close()
	sessionWait.Wait()
}

func TestWriteError2(t *testing.T) {
	_, connYang := net.Pipe()
	connYang.Close()

	sessionYang, err := NewSession(connYang, Yang, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYang.Serve(); err != nil {
			t.Fatal("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYang.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYang.Close()
	sessionWait.Wait()
}

func TestReadInvalidHeader(t *testing.T) {
	connYin, connYang := net.Pipe()

	sessionYin, err := NewSession(connYin, Yin, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			if err == nil {
				t.Fatal("Call should return error, got nil")
			}
		}
		sessionWait.Done()
	}()

	var header [4]byte
	connYang.Write(header[:])

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYin.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYin.Close()
	sessionWait.Wait()
}

func TestReadBodyError(t *testing.T) {
	connYin, connYang := net.Pipe()

	sessionYin, err := NewSession(connYin, Yin, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatal("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	var header [4]byte
	encodeHeader(header[:], byte(Yang), 10)
	connYang.Write(header[:])
	connYang.Close()

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYin.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYin.Close()
	sessionWait.Wait()
}

func TestConcurrent(t *testing.T) {
	connYin, connYang := net.Pipe()

	registryYin := NewRegistry()
	registryYang := NewRegistry()

	serviceYin := &Service{name: "Yin"}
	err := registryYin.Register(serviceYin)
	if err != nil {
		t.Fatalf("Register error: %v", err)
	}

	serviceYang := &Service{name: "Yang"}
	err = registryYang.Register(serviceYang)
	if err != nil {
		t.Fatalf("Register error: %v", err)
	}

	sessionYin, err := NewSession(connYin, Yin, registryYin, 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}
	sessionYang, err := NewSession(connYang, Yang, registryYang, 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(2)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatal("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()
	go func() {
		if err := sessionYang.Serve(); err != nil {
			t.Fatal("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	var GoroutineCount = 6
	var CallCount = 2
	var wg sync.WaitGroup
	wg.Add(GoroutineCount * 2)
	for i := 0; i < GoroutineCount; i++ {
		go func() {
			defer wg.Done()
			for i := 0; i <= CallCount; i++ {
				args := Args{"Anakin Skywalker"}
				reply := new(Reply)
				err := sessionYin.Call("Service.SayHi", args, reply)
				if err != nil {
					t.Fatalf("Call error: %v", err)
				}
				t.Logf("reply = %v\n", reply.Msg)
			}
		}()
		go func() {
			defer wg.Done()
			for i := 0; i <= CallCount; i++ {
				args := Args{"Darth Vader"}
				reply := new(Reply)
				err := sessionYang.Call("Service.SayHi", args, reply)
				if err != nil {
					t.Fatalf("Call error: %v", err)
				}
				t.Logf("reply = %v\n", reply.Msg)
			}
		}()

	}
	wg.Wait()

	sessionYin.Close()
	sessionYang.Close()
	sessionWait.Wait()
}

func ExampleSession() {
	var conn io.ReadWriteCloser

	// Create a registry, and register your available services
	registry := NewRegistry()
	registry.Register(&Service{})

	// TODO: Establish your connection before passing it to the session

	// Create a new session
	session, err := NewSession(conn, Yin, registry, 0)
	if err != nil {
		log.Fatal(err)
	}
	// Clean up session resources
	defer func() {
		if err := session.Close(); err != nil {
			log.Fatal(err)
		}
	}()

	// Start the event loop, this is a blocking call, so place it in a goroutine
	// if you need to move on.  The call will return when the connection is
	// terminated.
	if err = session.Serve(); err != nil {
		log.Fatal(err)
	}
}
<commit_msg>Fix go vet warnings<commit_after>package bidirpc

import (
	"fmt"
	"io"
	"log"
	"net"
	"sync"
	"sync/atomic"
	"testing"
)

type Args struct {
	Name string
}

type Reply struct {
	Msg string
}

type Service struct {
	name      string
	callCount int32
}

func (s *Service) SayHi(args Args, reply *Reply) error {
	reply.Msg = fmt.Sprintf("[%v] Hi %v, from %v", atomic.LoadInt32(&s.callCount), args.Name, s.name)
	atomic.AddInt32(&s.callCount, 1)
	return nil
}

func TestBasic(t *testing.T) {
	connYin, connYang := net.Pipe()

	registryYin := NewRegistry()
	registryYang := NewRegistry()

	serviceYin := &Service{name: "Yin"}
	err := registryYin.Register(serviceYin)
	if err != nil {
		t.Fatalf("Register error: %v", err)
	}

	serviceYang := &Service{name: "Yang"}
	err = registryYang.Register(serviceYang)
	if err != nil {
		t.Fatalf("Register error: %v", err)
	}

	sessionYin, err := NewSession(connYin, Yin, registryYin, 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}
	sessionYang, err := NewSession(connYang, Yang, registryYang, 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(2)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatalf("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()
	go func() {
		if err := sessionYang.Serve(); err != nil {
			t.Fatalf("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	for i := 0; i < 3; i++ {
		args := Args{"Windows"}
		reply := new(Reply)
		err = sessionYin.Call("Service.SayHi", args, reply)
		if err != nil {
			t.Fatalf("Call error: %v", err)
		}
		t.Logf("reply = %v\n", reply.Msg)

		args.Name = "OSX"
		err = sessionYang.Call("Service.SayHi", args, reply)
		if err != nil {
			t.Fatalf("Call error: %v", err)
		}
		t.Logf("reply = %v\n", reply.Msg)

		args.Name = "iOS"
		err = sessionYin.Call("Service.SayHi", args, reply)
		if err != nil {
			t.Fatalf("Call error: %v", err)
		}
		t.Logf("reply = %v\n", reply.Msg)
	}

	err = registryYang.RegisterName("NewService", serviceYang)
	if err != nil {
		t.Fatalf("RegisterName error: %v", err)
	}
	args := Args{"Linux"}
	reply := new(Reply)
	call := sessionYin.Go("NewService.SayHi", args, reply, nil)
	<-call.Done
	if call.Error != nil {
		t.Fatalf("Go error: %v", call.Error)
	}
	t.Logf("reply = %v\n", reply.Msg)

	sessionYin.Close()
	sessionYang.Close()
	sessionWait.Wait()
}

func TestReadError(t *testing.T) {
	connYin, connYang := net.Pipe()
	connYang.Close()

	sessionYin, err := NewSession(connYin, Yin, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatalf("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYin.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYin.Close()
	sessionWait.Wait()
}

func TestWriteError(t *testing.T) {
	connYin, _ := net.Pipe()
	connYin.Close()

	sessionYin, err := NewSession(connYin, Yin, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatalf("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYin.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYin.Close()
	sessionWait.Wait()
}

func TestWriteError2(t *testing.T) {
	_, connYang := net.Pipe()
	connYang.Close()

	sessionYang, err := NewSession(connYang, Yang, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYang.Serve(); err != nil {
			t.Fatalf("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYang.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYang.Close()
	sessionWait.Wait()
}

func TestReadInvalidHeader(t *testing.T) {
	connYin, connYang := net.Pipe()

	sessionYin, err := NewSession(connYin, Yin, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			if err == nil {
				t.Fatal("Call should return error, got nil")
			}
		}
		sessionWait.Done()
	}()

	var header [4]byte
	connYang.Write(header[:])

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYin.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYin.Close()
	sessionWait.Wait()
}

func TestReadBodyError(t *testing.T) {
	connYin, connYang := net.Pipe()

	sessionYin, err := NewSession(connYin, Yin, NewRegistry(), 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(1)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatalf("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	var header [4]byte
	encodeHeader(header[:], byte(Yang), 10)
	connYang.Write(header[:])
	connYang.Close()

	args := Args{"Windows"}
	reply := new(Reply)
	err = sessionYin.Call("Service.SayHi", args, reply)
	if err == nil {
		t.Fatal("Call should return error, got nil")
	}

	sessionYin.Close()
	sessionWait.Wait()
}

func TestConcurrent(t *testing.T) {
	connYin, connYang := net.Pipe()

	registryYin := NewRegistry()
	registryYang := NewRegistry()

	serviceYin := &Service{name: "Yin"}
	err := registryYin.Register(serviceYin)
	if err != nil {
		t.Fatalf("Register error: %v", err)
	}

	serviceYang := &Service{name: "Yang"}
	err = registryYang.Register(serviceYang)
	if err != nil {
		t.Fatalf("Register error: %v", err)
	}

	sessionYin, err := NewSession(connYin, Yin, registryYin, 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}
	sessionYang, err := NewSession(connYang, Yang, registryYang, 0)
	if err != nil {
		t.Fatalf("NewSession error: %v", err)
	}

	sessionWait := sync.WaitGroup{}
	sessionWait.Add(2)
	go func() {
		if err := sessionYin.Serve(); err != nil {
			t.Fatalf("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()
	go func() {
		if err := sessionYang.Serve(); err != nil {
			t.Fatalf("Eventloop error: %v", err)
		}
		sessionWait.Done()
	}()

	var GoroutineCount = 6
	var CallCount = 2
	var wg sync.WaitGroup
	wg.Add(GoroutineCount * 2)
	for i := 0; i < GoroutineCount; i++ {
		go func() {
			defer wg.Done()
			for i := 0; i <= CallCount; i++ {
				args := Args{"Anakin Skywalker"}
				reply := new(Reply)
				err := sessionYin.Call("Service.SayHi", args, reply)
				if err != nil {
					t.Fatalf("Call error: %v", err)
				}
				t.Logf("reply = %v\n", reply.Msg)
			}
		}()
		go func() {
			defer wg.Done()
			for i := 0; i <= CallCount; i++ {
				args := Args{"Darth Vader"}
				reply := new(Reply)
				err := sessionYang.Call("Service.SayHi", args, reply)
				if err != nil {
					t.Fatalf("Call error: %v", err)
				}
				t.Logf("reply = %v\n", reply.Msg)
			}
		}()

	}
	wg.Wait()

	sessionYin.Close()
	sessionYang.Close()
	sessionWait.Wait()
}

func ExampleSession() {
	var conn io.ReadWriteCloser

	// Create a registry, and register your available services
	registry := NewRegistry()
	registry.Register(&Service{})

	// TODO: Establish your connection before passing it to the session

	// Create a new session
	session, err := NewSession(conn, Yin, registry, 0)
	if err != nil {
		log.Fatal(err)
	}
	// Clean up session resources
	defer func() {
		if err := session.Close(); err != nil {
			log.Fatal(err)
		}
	}()

	// Start the event loop, this is a blocking call, so place it in a goroutine
	// if you need to move on.  The call will return when the connection is
	// terminated.
	if err = session.Serve(); err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>// Copyright 2016-2017 Authors of Cilium
//
// 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 bpfdebug

import (
	"fmt"

	"github.com/cilium/cilium/common"
)

// Must be synchronized with <bpf/lib/common.h>
const (
	MessageTypeUnspec = iota
	MessageTypeDrop
	MessageTypeDebug
	MessageTypeCapture
)

// must be in sync with <bpf/lib/dbg.h>
const (
	DbgCaptureUnspec = iota
	DbgCaptureFromLxc
	DbgCaptureFromNetdev
	DbgCaptureFromOverlay
	DbgCaptureDelivery
	DbgCaptureFromLb
	DbgCaptureAfterV46
	DbgCaptureAfterV64
	DbgCaptureProxyPre
	DbgCaptureProxyPost
)

// must be in sync with <bpf/lib/dbg.h>
const (
	DbgUnspec = iota
	DbgGeneric
	DbgLocalDelivery
	DbgEncap
	DbgLxcFound
	DbgPolicyDenied
	DbgCtLookup
	DbgCtMatch
	DbgCtCreated
	DbgCtCreated2
	DbgIcmp6Handle
	DbgIcmp6Request
	DbgIcmp6Ns
	DbgIcmp6TimeExceeded
	DbgCtVerdict
	DbgDecap
	DbgPortMap
	DbgErrorRet
	DbgToHost
	DbgToStack
	DbgPktHash
	DbgLb6LookupMaster
	DbgLb6LookupMasterFail
	DbgLb6LookupSlave
	DbgLb6LookupSlaveSuccess
	DbgLb6ReverseNatLookup
	DbgLb6ReverseNat
	DbgLb4LookupMaster
	DbgLb4LookupMasterFail
	DbgLb4LookupSlave
	DbgLb4LookupSlaveSuccess
	DbgLb4ReverseNatLookup
	DbgLb4ReverseNat
	DbgLb4LoopbackSnat
	DbgLb4LoopbackSnatRev
	DbgCtLookup4
	DbgRRSlaveSel
	DbgRevProxyLookup
	DbgRevProxyFound
	DbgRevProxyUpdate
	DbgL4Policy
)

// must be in sync with <bpf/lib/conntrack.h>
const (
	CtNew uint32 = iota
	CtEstablished
	CtReply
	CtRelated
)

var ctStateText = map[uint32]string{
	CtNew:         "New",
	CtEstablished: "Established",
	CtReply:       "Reply",
	CtRelated:     "Related",
}

func ctState(state uint32) string {
	txt, ok := ctStateText[state]
	if ok {
		return txt
	}

	return dropReason(uint8(state))
}

func ctInfo(arg1 uint32, arg2 uint32) string {
	return fmt.Sprintf("sport=%d dport=%d nexthdr=%d flags=%d",
		arg1>>16, arg1&0xFFFF, arg2>>8, arg2&0xFF)
}

func proxyInfo(arg1 uint32, arg2 uint32) string {
	sport := common.Swab16(uint16(arg1 >> 16))
	dport := common.Swab16(uint16(arg1 & 0xFFFF))
	return fmt.Sprintf("sport=%d dport=%d saddr=%x", sport, dport, arg2)
}

// DebugMsg is the message format of the debug message found in the BPF ring buffer
type DebugMsg struct {
	Type    uint8
	SubType uint8
	Source  uint16
	Hash    uint32
	Arg1    uint32
	Arg2    uint32
}

// Dump prints the debug message in a human readable format.
func (n *DebugMsg) Dump(data []byte, prefix string) {
	fmt.Printf("%s MARK %#x FROM %d DEBUG: ", prefix, n.Hash, n.Source)
	switch n.SubType {
	case DbgGeneric:
		fmt.Printf("No message, arg1=%d (%#x) arg2=%d (%#x)\n", n.Arg1, n.Arg1, n.Arg2, n.Arg2)
	case DbgLocalDelivery:
		fmt.Printf("Attempting local delivery for container id %d from seclabel %d\n", n.Arg1, n.Arg2)
	case DbgEncap:
		fmt.Printf("Encapsulating to node %d (%#x) from seclabel %d\n", n.Arg1, n.Arg1, n.Arg2)
	case DbgLxcFound:
		fmt.Printf("Local container found ifindex %d seclabel %d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgPolicyDenied:
		fmt.Printf("Policy evaluation would deny packet from %d to %d\n", n.Arg1, n.Arg2)
	case DbgCtLookup:
		fmt.Printf("CT lookup: %s\n", ctInfo(n.Arg1, n.Arg2))
	case DbgCtLookup4:
		fmt.Printf("CT lookup address: %x\n", n.Arg1)
	case DbgCtMatch:
		fmt.Printf("CT entry found lifetime=%d, revnat=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgCtCreated:
		fmt.Printf("CT created 1/2: %s\n", ctInfo(n.Arg1, n.Arg2))
	case DbgCtCreated2:
		fmt.Printf("CT created 2/2: %x revnat=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgCtVerdict:
		fmt.Printf("CT verdict: %s\n", ctState(n.Arg1))
	case DbgIcmp6Handle:
		fmt.Printf("Handling ICMPv6 type=%d\n", n.Arg1)
	case DbgIcmp6Request:
		fmt.Printf("ICMPv6 echo request for router offset=%d\n", n.Arg1)
	case DbgIcmp6Ns:
		fmt.Printf("ICMPv6 neighbour soliciation for address %x:%x\n", n.Arg1, n.Arg2)
	case DbgIcmp6TimeExceeded:
		fmt.Printf("Sending ICMPv6 time exceeded\n")
	case DbgDecap:
		fmt.Printf("Tunnel decap: id=%d flowlabel=%x\n", n.Arg1, n.Arg2)
	case DbgPortMap:
		fmt.Printf("Mapping port from=%d to=%d\n", n.Arg1, n.Arg2)
	case DbgErrorRet:
		fmt.Printf("BPF function %d returned error %d\n", n.Arg1, n.Arg2)
	case DbgToHost:
		fmt.Printf("Going to host, policy-skip=%d\n", n.Arg1)
	case DbgToStack:
		fmt.Printf("Going to the stack, policy-skip=%d\n", n.Arg1)
	case DbgPktHash:
		fmt.Printf("Packet hash=%d (%#x), selected_service=%d\n", n.Arg1, n.Arg1, n.Arg2)
	case DbgRRSlaveSel:
		fmt.Printf("RR slave selection hash=%d (%#x), selected_service=%d\n", n.Arg1, n.Arg1, n.Arg2)
	case DbgLb6LookupMaster:
		fmt.Printf("Master service lookup, addr.p4=%x key.dport=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb6LookupMasterFail:
		fmt.Printf("Master service lookup failed, addr.p2=%x addr.p3=%x\n", n.Arg1, n.Arg2)
	case DbgLb6LookupSlave, DbgLb4LookupSlave:
		fmt.Printf("Slave service lookup: slave=%d, dport=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb6LookupSlaveSuccess:
		fmt.Printf("Slave service lookup result: target.p4=%x port=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb6ReverseNatLookup, DbgLb4ReverseNatLookup:
		fmt.Printf("Reverse NAT lookup, index=%d\n", common.Swab16(uint16(n.Arg1)))
	case DbgLb6ReverseNat:
		fmt.Printf("Performing reverse NAT, address.p4=%x port=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb4LookupMaster:
		fmt.Printf("Master service lookup, addr=%x key.dport=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb4LookupMasterFail:
		fmt.Printf("Master service lookup failed\n")
	case DbgLb4LookupSlaveSuccess:
		fmt.Printf("Slave service lookup result: target=%x port=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb4ReverseNat:
		fmt.Printf("Performing reverse NAT, address=%x port=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb4LoopbackSnat:
		fmt.Printf("Loopback SNAT from=%x to=%x\n", n.Arg1, n.Arg2)
	case DbgLb4LoopbackSnatRev:
		fmt.Printf("Loopback reverse SNAT from=%x to=%x\n", n.Arg1, n.Arg2)
	case DbgRevProxyLookup:
		fmt.Printf("Reverse proxy lookup, %s\n", proxyInfo(n.Arg1, n.Arg2))
	case DbgRevProxyFound:
		fmt.Printf("Reverse proxy entry found, orig-daddr=%x orig-dport=%d\n", n.Arg1, n.Arg2)
	case DbgRevProxyUpdate:
		fmt.Printf("Reverse proxy updated, %s\n", proxyInfo(n.Arg1, n.Arg2))
	case DbgL4Policy:
		fmt.Printf("Resolved L4 policy to: %d / %d\n", common.Swab16(uint16(n.Arg1)), n.Arg2)
	default:
		fmt.Printf("Unknown message type=%d arg1=%d arg2=%d\n", n.SubType, n.Arg1, n.Arg2)
	}
}

const (
	// DebugCaptureLen is the amount of packet data in a packet capture message
	DebugCaptureLen = 20
)

// DebugCapture is the metadata sent along with a captured packet frame
type DebugCapture struct {
	Type    uint8
	SubType uint8
	Source  uint16
	Hash    uint32
	Len     uint32
	OrigLen uint32
	Arg1    uint32
	// data
}

// Dump prints the captured packet in human readable format
func (n *DebugCapture) Dump(dissect bool, data []byte, prefix string) {
	fmt.Printf("%s MARK %#x FROM %d DEBUG: %d bytes ", prefix, n.Hash, n.Source, n.Len)
	switch n.SubType {
	case DbgCaptureFromLxc:
		fmt.Printf("Incoming packet from container ifindex %d\n", n.Arg1)
	case DbgCaptureFromNetdev:
		fmt.Printf("Incoming packet from netdev ifindex %d\n", n.Arg1)
	case DbgCaptureFromOverlay:
		fmt.Printf("Incoming packet from overlay ifindex %d\n", n.Arg1)
	case DbgCaptureDelivery:
		fmt.Printf("Delivery to ifindex %d\n", n.Arg1)
	case DbgCaptureFromLb:
		fmt.Printf("Incoming packet to load balancer on ifindex %d\n", n.Arg1)
	case DbgCaptureAfterV46:
		fmt.Printf("Packet after nat46 ifindex %d\n", n.Arg1)
	case DbgCaptureAfterV64:
		fmt.Printf("Packet after nat64 ifindex %d\n", n.Arg1)
	case DbgCaptureProxyPre:
		fmt.Printf("Packet to proxy port %d (Pre)\n", common.Swab16(uint16(n.Arg1)))
	case DbgCaptureProxyPost:
		fmt.Printf("Packet to proxy port %d (Post)\n", common.Swab16(uint16(n.Arg1)))
	default:
		fmt.Printf("Unknown message type=%d arg1=%d\n", n.SubType, n.Arg1)
	}

	if n.Len > 0 && len(data) > DebugCaptureLen {
		Dissect(dissect, data[DebugCaptureLen:])
	}
}
<commit_msg>pkg/bpfdebug: Print string for ct direction<commit_after>// Copyright 2016-2017 Authors of Cilium
//
// 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 bpfdebug

import (
	"fmt"

	"github.com/cilium/cilium/common"
)

// Must be synchronized with <bpf/lib/common.h>
const (
	MessageTypeUnspec = iota
	MessageTypeDrop
	MessageTypeDebug
	MessageTypeCapture
)

// must be in sync with <bpf/lib/dbg.h>
const (
	DbgCaptureUnspec = iota
	DbgCaptureFromLxc
	DbgCaptureFromNetdev
	DbgCaptureFromOverlay
	DbgCaptureDelivery
	DbgCaptureFromLb
	DbgCaptureAfterV46
	DbgCaptureAfterV64
	DbgCaptureProxyPre
	DbgCaptureProxyPost
)

// must be in sync with <bpf/lib/dbg.h>
const (
	DbgUnspec = iota
	DbgGeneric
	DbgLocalDelivery
	DbgEncap
	DbgLxcFound
	DbgPolicyDenied
	DbgCtLookup
	DbgCtMatch
	DbgCtCreated
	DbgCtCreated2
	DbgIcmp6Handle
	DbgIcmp6Request
	DbgIcmp6Ns
	DbgIcmp6TimeExceeded
	DbgCtVerdict
	DbgDecap
	DbgPortMap
	DbgErrorRet
	DbgToHost
	DbgToStack
	DbgPktHash
	DbgLb6LookupMaster
	DbgLb6LookupMasterFail
	DbgLb6LookupSlave
	DbgLb6LookupSlaveSuccess
	DbgLb6ReverseNatLookup
	DbgLb6ReverseNat
	DbgLb4LookupMaster
	DbgLb4LookupMasterFail
	DbgLb4LookupSlave
	DbgLb4LookupSlaveSuccess
	DbgLb4ReverseNatLookup
	DbgLb4ReverseNat
	DbgLb4LoopbackSnat
	DbgLb4LoopbackSnatRev
	DbgCtLookup4
	DbgRRSlaveSel
	DbgRevProxyLookup
	DbgRevProxyFound
	DbgRevProxyUpdate
	DbgL4Policy
)

// must be in sync with <bpf/lib/conntrack.h>
const (
	CtNew uint32 = iota
	CtEstablished
	CtReply
	CtRelated
)

var ctStateText = map[uint32]string{
	CtNew:         "New",
	CtEstablished: "Established",
	CtReply:       "Reply",
	CtRelated:     "Related",
}

const (
	ctEgress  = 0
	ctIngress = 1
)

var ctDirection = map[int]string{
	ctEgress:  "egress",
	ctIngress: "ingress",
}

func ctState(state uint32) string {
	txt, ok := ctStateText[state]
	if ok {
		return txt
	}

	return dropReason(uint8(state))
}

func ctInfo(arg1 uint32, arg2 uint32) string {
	return fmt.Sprintf("sport=%d dport=%d nexthdr=%d flags=%d",
		arg1>>16, arg1&0xFFFF, arg2>>8, arg2&0xFF)
}

func proxyInfo(arg1 uint32, arg2 uint32) string {
	sport := common.Swab16(uint16(arg1 >> 16))
	dport := common.Swab16(uint16(arg1 & 0xFFFF))
	return fmt.Sprintf("sport=%d dport=%d saddr=%x", sport, dport, arg2)
}

// DebugMsg is the message format of the debug message found in the BPF ring buffer
type DebugMsg struct {
	Type    uint8
	SubType uint8
	Source  uint16
	Hash    uint32
	Arg1    uint32
	Arg2    uint32
}

// Dump prints the debug message in a human readable format.
func (n *DebugMsg) Dump(data []byte, prefix string) {
	fmt.Printf("%s MARK %#x FROM %d DEBUG: ", prefix, n.Hash, n.Source)
	switch n.SubType {
	case DbgGeneric:
		fmt.Printf("No message, arg1=%d (%#x) arg2=%d (%#x)\n", n.Arg1, n.Arg1, n.Arg2, n.Arg2)
	case DbgLocalDelivery:
		fmt.Printf("Attempting local delivery for container id %d from seclabel %d\n", n.Arg1, n.Arg2)
	case DbgEncap:
		fmt.Printf("Encapsulating to node %d (%#x) from seclabel %d\n", n.Arg1, n.Arg1, n.Arg2)
	case DbgLxcFound:
		fmt.Printf("Local container found ifindex %d seclabel %d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgPolicyDenied:
		fmt.Printf("Policy evaluation would deny packet from %d to %d\n", n.Arg1, n.Arg2)
	case DbgCtLookup:
		fmt.Printf("CT lookup: %s\n", ctInfo(n.Arg1, n.Arg2))
	case DbgCtLookup4:
		fmt.Printf("CT lookup address: %x\n", n.Arg1)
	case DbgCtMatch:
		fmt.Printf("CT entry found lifetime=%d, revnat=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgCtCreated:
		fmt.Printf("CT created 1/2: %s\n", ctInfo(n.Arg1, n.Arg2))
	case DbgCtCreated2:
		fmt.Printf("CT created 2/2: %x revnat=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgCtVerdict:
		fmt.Printf("CT verdict: %s\n", ctState(n.Arg1))
	case DbgIcmp6Handle:
		fmt.Printf("Handling ICMPv6 type=%d\n", n.Arg1)
	case DbgIcmp6Request:
		fmt.Printf("ICMPv6 echo request for router offset=%d\n", n.Arg1)
	case DbgIcmp6Ns:
		fmt.Printf("ICMPv6 neighbour soliciation for address %x:%x\n", n.Arg1, n.Arg2)
	case DbgIcmp6TimeExceeded:
		fmt.Printf("Sending ICMPv6 time exceeded\n")
	case DbgDecap:
		fmt.Printf("Tunnel decap: id=%d flowlabel=%x\n", n.Arg1, n.Arg2)
	case DbgPortMap:
		fmt.Printf("Mapping port from=%d to=%d\n", n.Arg1, n.Arg2)
	case DbgErrorRet:
		fmt.Printf("BPF function %d returned error %d\n", n.Arg1, n.Arg2)
	case DbgToHost:
		fmt.Printf("Going to host, policy-skip=%d\n", n.Arg1)
	case DbgToStack:
		fmt.Printf("Going to the stack, policy-skip=%d\n", n.Arg1)
	case DbgPktHash:
		fmt.Printf("Packet hash=%d (%#x), selected_service=%d\n", n.Arg1, n.Arg1, n.Arg2)
	case DbgRRSlaveSel:
		fmt.Printf("RR slave selection hash=%d (%#x), selected_service=%d\n", n.Arg1, n.Arg1, n.Arg2)
	case DbgLb6LookupMaster:
		fmt.Printf("Master service lookup, addr.p4=%x key.dport=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb6LookupMasterFail:
		fmt.Printf("Master service lookup failed, addr.p2=%x addr.p3=%x\n", n.Arg1, n.Arg2)
	case DbgLb6LookupSlave, DbgLb4LookupSlave:
		fmt.Printf("Slave service lookup: slave=%d, dport=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb6LookupSlaveSuccess:
		fmt.Printf("Slave service lookup result: target.p4=%x port=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb6ReverseNatLookup, DbgLb4ReverseNatLookup:
		fmt.Printf("Reverse NAT lookup, index=%d\n", common.Swab16(uint16(n.Arg1)))
	case DbgLb6ReverseNat:
		fmt.Printf("Performing reverse NAT, address.p4=%x port=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb4LookupMaster:
		fmt.Printf("Master service lookup, addr=%x key.dport=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb4LookupMasterFail:
		fmt.Printf("Master service lookup failed\n")
	case DbgLb4LookupSlaveSuccess:
		fmt.Printf("Slave service lookup result: target=%x port=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb4ReverseNat:
		fmt.Printf("Performing reverse NAT, address=%x port=%d\n", n.Arg1, common.Swab16(uint16(n.Arg2)))
	case DbgLb4LoopbackSnat:
		fmt.Printf("Loopback SNAT from=%x to=%x\n", n.Arg1, n.Arg2)
	case DbgLb4LoopbackSnatRev:
		fmt.Printf("Loopback reverse SNAT from=%x to=%x\n", n.Arg1, n.Arg2)
	case DbgRevProxyLookup:
		fmt.Printf("Reverse proxy lookup, %s\n", proxyInfo(n.Arg1, n.Arg2))
	case DbgRevProxyFound:
		fmt.Printf("Reverse proxy entry found, orig-daddr=%x orig-dport=%d\n", n.Arg1, n.Arg2)
	case DbgRevProxyUpdate:
		fmt.Printf("Reverse proxy updated, %s\n", proxyInfo(n.Arg1, n.Arg2))
	case DbgL4Policy:
		fmt.Printf("Resolved L4 policy to: %d / %s\n",
			common.Swab16(uint16(n.Arg1)), ctDirection[int(n.Arg2)])
	default:
		fmt.Printf("Unknown message type=%d arg1=%d arg2=%d\n", n.SubType, n.Arg1, n.Arg2)
	}
}

const (
	// DebugCaptureLen is the amount of packet data in a packet capture message
	DebugCaptureLen = 20
)

// DebugCapture is the metadata sent along with a captured packet frame
type DebugCapture struct {
	Type    uint8
	SubType uint8
	Source  uint16
	Hash    uint32
	Len     uint32
	OrigLen uint32
	Arg1    uint32
	// data
}

// Dump prints the captured packet in human readable format
func (n *DebugCapture) Dump(dissect bool, data []byte, prefix string) {
	fmt.Printf("%s MARK %#x FROM %d DEBUG: %d bytes ", prefix, n.Hash, n.Source, n.Len)
	switch n.SubType {
	case DbgCaptureFromLxc:
		fmt.Printf("Incoming packet from container ifindex %d\n", n.Arg1)
	case DbgCaptureFromNetdev:
		fmt.Printf("Incoming packet from netdev ifindex %d\n", n.Arg1)
	case DbgCaptureFromOverlay:
		fmt.Printf("Incoming packet from overlay ifindex %d\n", n.Arg1)
	case DbgCaptureDelivery:
		fmt.Printf("Delivery to ifindex %d\n", n.Arg1)
	case DbgCaptureFromLb:
		fmt.Printf("Incoming packet to load balancer on ifindex %d\n", n.Arg1)
	case DbgCaptureAfterV46:
		fmt.Printf("Packet after nat46 ifindex %d\n", n.Arg1)
	case DbgCaptureAfterV64:
		fmt.Printf("Packet after nat64 ifindex %d\n", n.Arg1)
	case DbgCaptureProxyPre:
		fmt.Printf("Packet to proxy port %d (Pre)\n", common.Swab16(uint16(n.Arg1)))
	case DbgCaptureProxyPost:
		fmt.Printf("Packet to proxy port %d (Post)\n", common.Swab16(uint16(n.Arg1)))
	default:
		fmt.Printf("Unknown message type=%d arg1=%d\n", n.SubType, n.Arg1)
	}

	if n.Len > 0 && len(data) > DebugCaptureLen {
		Dissect(dissect, data[DebugCaptureLen:])
	}
}
<|endoftext|>


<commit_before>package peco

import (
	"encoding/json"
	"fmt"
	"os"
	"unicode"

	"github.com/nsf/termbox-go"
)

type KeymapHandler func(*Input, termbox.Event)
type Keymap map[termbox.Key]KeymapHandler
type KeymapStringKey string
type KeymapStringHandler string

// This map is populated using some magic numbers, which must match
// the values defined in termbox-go. Verification against the actual
// termbox constants are done in the test
var stringToKey = map[string]termbox.Key{}

func init() {
	fidx := 12
	for k := termbox.KeyF1; k > termbox.KeyF12; k-- {
		sk := fmt.Sprintf("F%d", fidx)
		stringToKey[sk] = k
		fidx--
	}

	names := []string{
		"Insert",
		"Delete",
		"Home",
		"End",
		"Pgup",
		"Pgdn",
		"ArrowUp",
		"ArrowDown",
		"ArrowLeft",
		"ArrowRight",
	}
	for i, n := range names {
		stringToKey[n] = termbox.Key(int(termbox.KeyF12) - (i + 1))
	}

	names = []string{
		"Left",
		"Middle",
		"Right",
	}
	for i, n := range names {
		sk := fmt.Sprintf("Mouse%s", n)
		stringToKey[sk] = termbox.Key(int(termbox.KeyArrowRight) - (i + 2))
	}

	whacky := [][]string{
		{"~", "2", "Space"},
		{"a"},
		{"b"},
		{"c"},
		{"d"},
		{"e"},
		{"f"},
		{"g"},
		{"h"},
		{"i"},
		{"j"},
		{"k"},
		{"l"},
		{"m"},
		{"n"},
		{"o"},
		{"p"},
		{"q"},
		{"r"},
		{"s"},
		{"t"},
		{"u"},
		{"v"},
		{"w"},
		{"x"},
		{"y"},
		{"z"},
		{"[", "3"},
		{"4", "\\"},
		{"5", "]"},
		{"6"},
		{"7", "/", "_"},
	}
	for i, list := range whacky {
		for _, n := range list {
			sk := fmt.Sprintf("C-%s", n)
			stringToKey[sk] = termbox.Key(int(termbox.KeyCtrlTilde) + i)
		}
	}

	stringToKey["BS"] = termbox.KeyBackspace
	stringToKey["Tab"] = termbox.KeyTab
	stringToKey["Enter"] = termbox.KeyEnter
	stringToKey["Esc"] = termbox.KeyEsc
	stringToKey["Space"] = termbox.KeySpace
	stringToKey["BS2"] = termbox.KeyBackspace2
	stringToKey["C-8"] = termbox.KeyCtrl8

	//	panic(fmt.Sprintf("%#q", stringToKey))
}

func handleAcceptChar(i *Input, ev termbox.Event) {
	if ev.Key == termbox.KeySpace {
		ev.Ch = ' '
	}

	if ev.Ch > 0 {
		if len(i.query) == i.caretPos {
			i.query = append(i.query, ev.Ch)
		} else {
			buf := make([]rune, len(i.query)+1)
			copy(buf, i.query[:i.caretPos])
			buf[i.caretPos] = ev.Ch
			copy(buf[i.caretPos+1:], i.query[i.caretPos:])
			i.query = buf
		}
		i.caretPos++
		i.ExecQuery(string(i.query))
	}
}

// peco.Finish -> end program, exit with success
func handleFinish(i *Input, _ termbox.Event) {
	if len(i.current) == 1 {
		i.result = i.current[0].line
	} else if i.selectedLine > 0 && i.selectedLine < len(i.current) {
		i.result = i.current[i.selectedLine-1].line
	}
	i.Finish()
}

// peco.Cancel -> end program, exit with failure
func handleCancel(i *Input, ev termbox.Event) {
	i.ExitStatus = 1
	i.Finish()
}

func handleSelectPrevious(i *Input, ev termbox.Event) {
	i.PagingCh() <- ToPrevLine
	i.DrawMatches(nil)
}

func handleSelectNext(i *Input, ev termbox.Event) {
	i.PagingCh() <- ToNextLine
	i.DrawMatches(nil)
}

func handleSelectPreviousPage(i *Input, ev termbox.Event) {
	i.PagingCh() <- ToPrevPage
	i.DrawMatches(nil)
}

func handleSelectNextPage(i *Input, ev termbox.Event) {
	i.PagingCh() <- ToNextPage
	i.DrawMatches(nil)
}

func handleForwardWord(i *Input, _ termbox.Event) {
	if i.caretPos >= len(i.query) {
		return
	}

	foundSpace := false
	for pos := i.caretPos; pos < len(i.query); pos++ {
		r := i.query[pos]
		if foundSpace {
			if !unicode.IsSpace(r) {
				i.caretPos = pos
				i.DrawMatches(nil)
				return
			}
		} else {
			if unicode.IsSpace(r) {
				foundSpace = true
			}
		}
	}

	// not found. just move to the end of the buffer
	i.caretPos = len(i.query)
	i.DrawMatches(nil)

}

func handleBackwardWord(i *Input, _ termbox.Event) {
	if i.caretPos == 0 {
		return
	}

	if i.caretPos >= len(i.query) {
		i.caretPos--
	}

	// if we start from a whitespace-ish position, we should
	// rewind to the end of the previous word, and then do the
	// search all over again
SEARCH_PREV_WORD:
	if unicode.IsSpace(i.query[i.caretPos]) {
		for pos := i.caretPos; pos > 0; pos-- {
			if !unicode.IsSpace(i.query[pos]) {
				i.caretPos = pos
				break
			}
		}
	}

	// if we start from the first character of a word, we
	// should attempt to move back and search for the previous word
	if i.caretPos > 0 && unicode.IsSpace(i.query[i.caretPos-1]) {
		i.caretPos--
		goto SEARCH_PREV_WORD
	}

	// Now look for a space
	for pos := i.caretPos; pos > 0; pos-- {
		if unicode.IsSpace(i.query[pos]) {
			i.caretPos = pos + 1
			i.DrawMatches(nil)
			return
		}
	}

	// not found. just move to the beginning of the buffer
	i.caretPos = 0
	i.DrawMatches(nil)
}

func handleForwardChar(i *Input, _ termbox.Event) {
	if i.caretPos >= len(i.query) {
		return
	}
	i.caretPos++
	i.DrawMatches(nil)
}

func handleBackwardChar(i *Input, _ termbox.Event) {
	if i.caretPos <= 0 {
		return
	}
	i.caretPos--
	i.DrawMatches(nil)
}

func handleBeginningOfLine(i *Input, _ termbox.Event) {
	i.caretPos = 0
	i.DrawMatches(nil)
}

func handleEndOfLine(i *Input, _ termbox.Event) {
	i.caretPos = len(i.query)
	i.DrawMatches(nil)
}

func handleKillEndOfLine(i *Input, _ termbox.Event) {
	if len(i.query) <= i.caretPos {
		return
	}

	i.query = i.query[0:i.caretPos]
	i.DrawMatches(nil)
}

func handleDeleteForwardChar(i *Input, _ termbox.Event) {
	if len(i.query) <= i.caretPos {
		return
	}

	buf := make([]rune, len(i.query)-1)
	copy(buf, i.query[:i.caretPos])
	copy(buf[i.caretPos:], i.query[i.caretPos+1:])
	i.query = buf
	if len(i.query) > 0 {
		i.ExecQuery(string(i.query))
		return
	}

	i.current = nil
	i.DrawMatches(nil)
}

func handleDeleteForwardWord(i *Input, _ termbox.Event) {
	if len(i.query) <= i.caretPos {
		return
	}

	for pos := i.caretPos; pos < len(i.query); pos++ {
		if pos == len(i.query) - 1 {
			i.query = i.query[:i.caretPos]
			break
		}

		if unicode.IsSpace(i.query[pos]) {
			buf := make([]rune, len(i.query) - (pos - i.caretPos))
			copy(buf, i.query[:i.caretPos])
			copy(buf[i.caretPos:], i.query[pos:])
			i.query = buf
			break
		}
	}

	if len(i.query) > 0 {
		i.ExecQuery(string(i.query))
		return
	}

	i.current = nil
	i.DrawMatches(nil)
}

func handleDeleteBackwardChar(i *Input, ev termbox.Event) {
	if len(i.query) <= 0 {
		return
	}

	switch i.caretPos {
	case 0:
		// No op
		return
	case len(i.query):
		i.query = i.query[:len(i.query)-1]
	default:
		buf := make([]rune, len(i.query)-1)
		copy(buf, i.query[:i.caretPos])
		copy(buf[i.caretPos-1:], i.query[i.caretPos:])
		i.query = buf
	}
	i.caretPos--
	if len(i.query) > 0 {
		i.ExecQuery(string(i.query))
		return
	}

	i.current = nil
	i.DrawMatches(nil)
}

func (ksk KeymapStringKey) ToKey() (k termbox.Key, err error) {
	k, ok := stringToKey[string(ksk)]
	if !ok {
		err = fmt.Errorf("No such key %s", ksk)
	}
	return
}

func (ksh KeymapStringHandler) ToHandler() (h KeymapHandler, err error) {
	switch ksh {
	case "peco.KillEndOfLine":
		h = handleKillEndOfLine
	case "peco.BeginningOfLine":
		h = handleBeginningOfLine
	case "peco.EndOfLine":
		h = handleEndOfLine
	case "peco.ForwardChar":
		h = handleForwardChar
	case "peco.BackwardChar":
		h = handleBackwardChar
	case "peco.ForwardWord":
		h = handleForwardWord
	case "peco.BackwardWord":
		h = handleBackwardWord
	case "peco.DeleteForwardChar":
		h = handleDeleteForwardChar
	case "peco.DeleteBackwardChar":
		h = handleDeleteBackwardChar
	case "peco.DeleteForwardWord":
		h = handleDeleteForwardWord
	case "peco.SelectPreviousPage":
		h = handleSelectPreviousPage
	case "peco.SelectNextPage":
		h = handleSelectNextPage
	case "peco.SelectPrevious":
		h = handleSelectPrevious
	case "peco.SelectNext":
		h = handleSelectNext
	case "peco.Finish":
		h = handleFinish
	case "peco.Cancel":
		h = handleCancel
	default:
		err = fmt.Errorf("No such handler %s", ksh)
	}
	return
}

func NewKeymap() Keymap {
	return Keymap{
		termbox.KeyEsc:        handleCancel,
		termbox.KeyEnter:      handleFinish,
		termbox.KeyArrowUp:    handleSelectPrevious,
		termbox.KeyCtrlK:      handleSelectPrevious,
		termbox.KeyArrowDown:  handleSelectNext,
		termbox.KeyCtrlJ:      handleSelectNext,
		termbox.KeyArrowLeft:  handleSelectPreviousPage,
		termbox.KeyArrowRight: handleSelectNextPage,
		termbox.KeyBackspace:  handleDeleteBackwardChar,
		termbox.KeyBackspace2: handleDeleteBackwardChar,
	}
}

func (km Keymap) Handler(k termbox.Key) KeymapHandler {
	h, ok := km[k]
	if ok {
		return h
	}
	return handleAcceptChar
}

func (km Keymap) UnmarshalJSON(buf []byte) error {
	raw := map[string]string{}
	if err := json.Unmarshal(buf, &raw); err != nil {
		return err
	}

	for ks, vs := range raw {
		k, err := KeymapStringKey(ks).ToKey()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Unknown key %s", ks)
			continue
		}

		v, err := KeymapStringHandler(vs).ToHandler()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Unknown handler %s", vs)
			continue
		}

		km[k] = v
	}

	return nil
}
<commit_msg>Implement DeleteBackwardWord<commit_after>package peco

import (
	"encoding/json"
	"fmt"
	"os"
	"unicode"

	"github.com/nsf/termbox-go"
)

type KeymapHandler func(*Input, termbox.Event)
type Keymap map[termbox.Key]KeymapHandler
type KeymapStringKey string
type KeymapStringHandler string

// This map is populated using some magic numbers, which must match
// the values defined in termbox-go. Verification against the actual
// termbox constants are done in the test
var stringToKey = map[string]termbox.Key{}

func init() {
	fidx := 12
	for k := termbox.KeyF1; k > termbox.KeyF12; k-- {
		sk := fmt.Sprintf("F%d", fidx)
		stringToKey[sk] = k
		fidx--
	}

	names := []string{
		"Insert",
		"Delete",
		"Home",
		"End",
		"Pgup",
		"Pgdn",
		"ArrowUp",
		"ArrowDown",
		"ArrowLeft",
		"ArrowRight",
	}
	for i, n := range names {
		stringToKey[n] = termbox.Key(int(termbox.KeyF12) - (i + 1))
	}

	names = []string{
		"Left",
		"Middle",
		"Right",
	}
	for i, n := range names {
		sk := fmt.Sprintf("Mouse%s", n)
		stringToKey[sk] = termbox.Key(int(termbox.KeyArrowRight) - (i + 2))
	}

	whacky := [][]string{
		{"~", "2", "Space"},
		{"a"},
		{"b"},
		{"c"},
		{"d"},
		{"e"},
		{"f"},
		{"g"},
		{"h"},
		{"i"},
		{"j"},
		{"k"},
		{"l"},
		{"m"},
		{"n"},
		{"o"},
		{"p"},
		{"q"},
		{"r"},
		{"s"},
		{"t"},
		{"u"},
		{"v"},
		{"w"},
		{"x"},
		{"y"},
		{"z"},
		{"[", "3"},
		{"4", "\\"},
		{"5", "]"},
		{"6"},
		{"7", "/", "_"},
	}
	for i, list := range whacky {
		for _, n := range list {
			sk := fmt.Sprintf("C-%s", n)
			stringToKey[sk] = termbox.Key(int(termbox.KeyCtrlTilde) + i)
		}
	}

	stringToKey["BS"] = termbox.KeyBackspace
	stringToKey["Tab"] = termbox.KeyTab
	stringToKey["Enter"] = termbox.KeyEnter
	stringToKey["Esc"] = termbox.KeyEsc
	stringToKey["Space"] = termbox.KeySpace
	stringToKey["BS2"] = termbox.KeyBackspace2
	stringToKey["C-8"] = termbox.KeyCtrl8

	//	panic(fmt.Sprintf("%#q", stringToKey))
}

func handleAcceptChar(i *Input, ev termbox.Event) {
	if ev.Key == termbox.KeySpace {
		ev.Ch = ' '
	}

	if ev.Ch > 0 {
		if len(i.query) == i.caretPos {
			i.query = append(i.query, ev.Ch)
		} else {
			buf := make([]rune, len(i.query)+1)
			copy(buf, i.query[:i.caretPos])
			buf[i.caretPos] = ev.Ch
			copy(buf[i.caretPos+1:], i.query[i.caretPos:])
			i.query = buf
		}
		i.caretPos++
		i.ExecQuery(string(i.query))
	}
}

// peco.Finish -> end program, exit with success
func handleFinish(i *Input, _ termbox.Event) {
	if len(i.current) == 1 {
		i.result = i.current[0].line
	} else if i.selectedLine > 0 && i.selectedLine < len(i.current) {
		i.result = i.current[i.selectedLine-1].line
	}
	i.Finish()
}

// peco.Cancel -> end program, exit with failure
func handleCancel(i *Input, ev termbox.Event) {
	i.ExitStatus = 1
	i.Finish()
}

func handleSelectPrevious(i *Input, ev termbox.Event) {
	i.PagingCh() <- ToPrevLine
	i.DrawMatches(nil)
}

func handleSelectNext(i *Input, ev termbox.Event) {
	i.PagingCh() <- ToNextLine
	i.DrawMatches(nil)
}

func handleSelectPreviousPage(i *Input, ev termbox.Event) {
	i.PagingCh() <- ToPrevPage
	i.DrawMatches(nil)
}

func handleSelectNextPage(i *Input, ev termbox.Event) {
	i.PagingCh() <- ToNextPage
	i.DrawMatches(nil)
}

func handleForwardWord(i *Input, _ termbox.Event) {
	if i.caretPos >= len(i.query) {
		return
	}

	foundSpace := false
	for pos := i.caretPos; pos < len(i.query); pos++ {
		r := i.query[pos]
		if foundSpace {
			if !unicode.IsSpace(r) {
				i.caretPos = pos
				i.DrawMatches(nil)
				return
			}
		} else {
			if unicode.IsSpace(r) {
				foundSpace = true
			}
		}
	}

	// not found. just move to the end of the buffer
	i.caretPos = len(i.query)
	i.DrawMatches(nil)

}

func handleBackwardWord(i *Input, _ termbox.Event) {
	if i.caretPos == 0 {
		return
	}

	if i.caretPos >= len(i.query) {
		i.caretPos--
	}

	// if we start from a whitespace-ish position, we should
	// rewind to the end of the previous word, and then do the
	// search all over again
SEARCH_PREV_WORD:
	if unicode.IsSpace(i.query[i.caretPos]) {
		for pos := i.caretPos; pos > 0; pos-- {
			if !unicode.IsSpace(i.query[pos]) {
				i.caretPos = pos
				break
			}
		}
	}

	// if we start from the first character of a word, we
	// should attempt to move back and search for the previous word
	if i.caretPos > 0 && unicode.IsSpace(i.query[i.caretPos-1]) {
		i.caretPos--
		goto SEARCH_PREV_WORD
	}

	// Now look for a space
	for pos := i.caretPos; pos > 0; pos-- {
		if unicode.IsSpace(i.query[pos]) {
			i.caretPos = pos + 1
			i.DrawMatches(nil)
			return
		}
	}

	// not found. just move to the beginning of the buffer
	i.caretPos = 0
	i.DrawMatches(nil)
}

func handleForwardChar(i *Input, _ termbox.Event) {
	if i.caretPos >= len(i.query) {
		return
	}
	i.caretPos++
	i.DrawMatches(nil)
}

func handleBackwardChar(i *Input, _ termbox.Event) {
	if i.caretPos <= 0 {
		return
	}
	i.caretPos--
	i.DrawMatches(nil)
}

func handleBeginningOfLine(i *Input, _ termbox.Event) {
	i.caretPos = 0
	i.DrawMatches(nil)
}

func handleEndOfLine(i *Input, _ termbox.Event) {
	i.caretPos = len(i.query)
	i.DrawMatches(nil)
}

func handleKillEndOfLine(i *Input, _ termbox.Event) {
	if len(i.query) <= i.caretPos {
		return
	}

	i.query = i.query[0:i.caretPos]
	i.DrawMatches(nil)
}

func handleDeleteForwardChar(i *Input, _ termbox.Event) {
	if len(i.query) <= i.caretPos {
		return
	}

	buf := make([]rune, len(i.query)-1)
	copy(buf, i.query[:i.caretPos])
	copy(buf[i.caretPos:], i.query[i.caretPos+1:])
	i.query = buf
	if len(i.query) > 0 {
		i.ExecQuery(string(i.query))
		return
	}

	i.current = nil
	i.DrawMatches(nil)
}

func handleDeleteBackwardChar(i *Input, ev termbox.Event) {
	if len(i.query) <= 0 {
		return
	}

	switch i.caretPos {
	case 0:
		// No op
		return
	case len(i.query):
		i.query = i.query[:len(i.query)-1]
	default:
		buf := make([]rune, len(i.query)-1)
		copy(buf, i.query[:i.caretPos])
		copy(buf[i.caretPos-1:], i.query[i.caretPos:])
		i.query = buf
	}
	i.caretPos--
	if len(i.query) > 0 {
		i.ExecQuery(string(i.query))
		return
	}

	i.current = nil
	i.DrawMatches(nil)
}

func handleDeleteForwardWord(i *Input, _ termbox.Event) {
	if len(i.query) <= i.caretPos {
		return
	}

	for pos := i.caretPos; pos < len(i.query); pos++ {
		if pos == len(i.query) - 1 {
			i.query = i.query[:i.caretPos]
			break
		}

		if unicode.IsSpace(i.query[pos]) {
			buf := make([]rune, len(i.query) - (pos - i.caretPos))
			copy(buf, i.query[:i.caretPos])
			copy(buf[i.caretPos:], i.query[pos:])
			i.query = buf
			break
		}
	}

	if len(i.query) > 0 {
		i.ExecQuery(string(i.query))
		return
	}

	i.current = nil
	i.DrawMatches(nil)
}

func handleDeleteBackwardWord(i *Input, _ termbox.Event) {
	if i.caretPos == 0 {
		return
	}

	for pos := i.caretPos - 1; pos >= 0; pos-- {
		if pos == 0 {
			i.query = i.query[i.caretPos:]
			break
		}

		if unicode.IsSpace(i.query[pos]) {
			buf := make([]rune, len(i.query) - (i.caretPos - pos))
			copy(buf, i.query[:pos])
			copy(buf[pos:], i.query[i.caretPos:])
			i.query = buf
			i.caretPos = pos
			break
		}
	}

	if len(i.query) > 0 {
		i.ExecQuery(string(i.query))
		return
	}

	i.current = nil
	i.DrawMatches(nil)
}

func (ksk KeymapStringKey) ToKey() (k termbox.Key, err error) {
	k, ok := stringToKey[string(ksk)]
	if !ok {
		err = fmt.Errorf("No such key %s", ksk)
	}
	return
}

func (ksh KeymapStringHandler) ToHandler() (h KeymapHandler, err error) {
	switch ksh {
	case "peco.KillEndOfLine":
		h = handleKillEndOfLine
	case "peco.BeginningOfLine":
		h = handleBeginningOfLine
	case "peco.EndOfLine":
		h = handleEndOfLine
	case "peco.ForwardChar":
		h = handleForwardChar
	case "peco.BackwardChar":
		h = handleBackwardChar
	case "peco.ForwardWord":
		h = handleForwardWord
	case "peco.BackwardWord":
		h = handleBackwardWord
	case "peco.DeleteForwardChar":
		h = handleDeleteForwardChar
	case "peco.DeleteBackwardChar":
		h = handleDeleteBackwardChar
	case "peco.DeleteForwardWord":
		h = handleDeleteForwardWord
	case "peco.DeleteBackwardWord":
		h = handleDeleteBackwardWord
	case "peco.SelectPreviousPage":
		h = handleSelectPreviousPage
	case "peco.SelectNextPage":
		h = handleSelectNextPage
	case "peco.SelectPrevious":
		h = handleSelectPrevious
	case "peco.SelectNext":
		h = handleSelectNext
	case "peco.Finish":
		h = handleFinish
	case "peco.Cancel":
		h = handleCancel
	default:
		err = fmt.Errorf("No such handler %s", ksh)
	}
	return
}

func NewKeymap() Keymap {
	return Keymap{
		termbox.KeyEsc:        handleCancel,
		termbox.KeyEnter:      handleFinish,
		termbox.KeyArrowUp:    handleSelectPrevious,
		termbox.KeyCtrlK:      handleSelectPrevious,
		termbox.KeyArrowDown:  handleSelectNext,
		termbox.KeyCtrlJ:      handleSelectNext,
		termbox.KeyArrowLeft:  handleSelectPreviousPage,
		termbox.KeyArrowRight: handleSelectNextPage,
		termbox.KeyBackspace:  handleDeleteBackwardChar,
		termbox.KeyBackspace2: handleDeleteBackwardChar,
	}
}

func (km Keymap) Handler(k termbox.Key) KeymapHandler {
	h, ok := km[k]
	if ok {
		return h
	}
	return handleAcceptChar
}

func (km Keymap) UnmarshalJSON(buf []byte) error {
	raw := map[string]string{}
	if err := json.Unmarshal(buf, &raw); err != nil {
		return err
	}

	for ks, vs := range raw {
		k, err := KeymapStringKey(ks).ToKey()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Unknown key %s", ks)
			continue
		}

		v, err := KeymapStringHandler(vs).ToHandler()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Unknown handler %s", vs)
			continue
		}

		km[k] = v
	}

	return nil
}
<|endoftext|>


<commit_before>package apply

import (
	rbacv1 "k8s.io/api/rbac/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	v1 "kubevirt.io/client-go/api/v1"
	"kubevirt.io/client-go/log"
	"kubevirt.io/kubevirt/pkg/virt-operator/util"
)

func (r *Reconciler) backupRBACs() error {

	// Backup existing ClusterRoles
	objects := r.stores.ClusterRoleCache.List()
	for _, obj := range objects {
		cachedCr, ok := obj.(*rbacv1.ClusterRole)
		if !ok || !needsClusterRoleBackup(r.kv, r.stores, cachedCr) {
			continue
		}
		imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&cachedCr.ObjectMeta)
		if !ok {
			continue
		}

		err := r.backupRBAC(cachedCr.DeepCopy(), cachedCr.Name, string(cachedCr.UID), imageTag, imageRegistry, id, TypeClusterRole)
		if err != nil {
			return err
		}
	}

	// Backup existing ClusterRoleBindings
	objects = r.stores.ClusterRoleBindingCache.List()
	for _, obj := range objects {
		cachedCrb, ok := obj.(*rbacv1.ClusterRoleBinding)
		if !ok || !needsClusterRoleBindingBackup(r.kv, r.stores, cachedCrb) {
			continue
		}
		imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&cachedCrb.ObjectMeta)
		if !ok {
			continue
		}

		err := r.backupRBAC(cachedCrb.DeepCopy(), cachedCrb.Name, string(cachedCrb.UID), imageTag, imageRegistry, id, TypeClusterRole)
		if err != nil {
			return err
		}
	}

	// Backup existing Roles
	objects = r.stores.RoleCache.List()
	for _, obj := range objects {
		cachedCr, ok := obj.(*rbacv1.Role)
		if !ok || !needsRoleBackup(r.kv, r.stores, cachedCr) {
			continue
		}
		imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&cachedCr.ObjectMeta)
		if !ok {
			continue
		}

		err := r.backupRBAC(cachedCr.DeepCopy(), cachedCr.Name, string(cachedCr.UID), imageTag, imageRegistry, id, TypeClusterRole)
		if err != nil {
			return err
		}
	}

	// Backup existing RoleBindings
	objects = r.stores.RoleBindingCache.List()
	for _, obj := range objects {
		cachedRb, ok := obj.(*rbacv1.RoleBinding)
		if !ok || !needsRoleBindingBackup(r.kv, r.stores, cachedRb) {
			continue
		}
		imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&cachedRb.ObjectMeta)
		if ok {
			continue
		}

		err := r.backupRBAC(cachedRb.DeepCopy(), cachedRb.Name, string(cachedRb.UID), imageTag, imageRegistry, id, TypeClusterRole)
		if err != nil {
			return err
		}
	}

	return nil
}

func (r *Reconciler) backupRBAC(obj interface{}, name, UID, imageTag, imageRegistry, id string, roleType RoleType) error {
	meta := getRoleMetaObject(obj, roleType)
	*meta = metav1.ObjectMeta{
		GenerateName: name,
	}
	injectOperatorMetadata(r.kv, meta, imageTag, imageRegistry, id, true)
	meta.Annotations[v1.EphemeralBackupObject] = UID

	// Create backup
	createRole := r.getRoleCreateFunction(obj, roleType)
	err := createRole()
	if err != nil {
		return err
	}

	log.Log.V(2).Infof("backup %v %v created", getRoleTypeName(roleType), name)
	return nil
}

func needsClusterRoleBackup(kv *v1.KubeVirt, stores util.Stores, cr *rbacv1.ClusterRole) bool {

	shouldBackup := shouldBackupRBACObject(kv, &cr.ObjectMeta)
	imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&cr.ObjectMeta)
	if !shouldBackup || !ok {
		return false
	}

	// loop through cache and determine if there's an ephemeral backup
	// for this object already
	objects := stores.ClusterRoleCache.List()
	for _, obj := range objects {
		cachedCr, ok := obj.(*rbacv1.ClusterRole)

		if !ok ||
			cachedCr.DeletionTimestamp != nil ||
			cr.Annotations == nil {
			continue
		}

		uid, ok := cachedCr.Annotations[v1.EphemeralBackupObject]
		if !ok {
			// this is not an ephemeral backup object
			continue
		}

		if uid == string(cr.UID) && objectMatchesVersion(&cachedCr.ObjectMeta, imageTag, imageRegistry, id, kv.GetGeneration()) {
			// found backup. UID matches and versions match
			// note, it's possible for a single UID to have multiple backups with
			// different versions
			return false
		}
	}

	return true
}

func needsRoleBindingBackup(kv *v1.KubeVirt, stores util.Stores, rb *rbacv1.RoleBinding) bool {

	shouldBackup := shouldBackupRBACObject(kv, &rb.ObjectMeta)
	imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&rb.ObjectMeta)
	if !shouldBackup || !ok {
		return false
	}

	// loop through cache and determine if there's an ephemeral backup
	// for this object already
	objects := stores.RoleBindingCache.List()
	for _, obj := range objects {
		cachedRb, ok := obj.(*rbacv1.RoleBinding)

		if !ok ||
			cachedRb.DeletionTimestamp != nil ||
			rb.Annotations == nil {
			continue
		}

		uid, ok := cachedRb.Annotations[v1.EphemeralBackupObject]
		if !ok {
			// this is not an ephemeral backup object
			continue
		}

		if uid == string(rb.UID) && objectMatchesVersion(&cachedRb.ObjectMeta, imageTag, imageRegistry, id, kv.GetGeneration()) {
			// found backup. UID matches and versions match
			// note, it's possible for a single UID to have multiple backups with
			// different versions
			return false
		}
	}

	return true
}

func needsRoleBackup(kv *v1.KubeVirt, stores util.Stores, r *rbacv1.Role) bool {

	shouldBackup := shouldBackupRBACObject(kv, &r.ObjectMeta)
	imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&r.ObjectMeta)
	if !shouldBackup || !ok {
		return false
	}

	// loop through cache and determine if there's an ephemeral backup
	// for this object already
	objects := stores.RoleCache.List()
	for _, obj := range objects {
		cachedR, ok := obj.(*rbacv1.Role)

		if !ok ||
			cachedR.DeletionTimestamp != nil ||
			r.Annotations == nil {
			continue
		}

		uid, ok := cachedR.Annotations[v1.EphemeralBackupObject]
		if !ok {
			// this is not an ephemeral backup object
			continue
		}

		if uid == string(r.UID) && objectMatchesVersion(&cachedR.ObjectMeta, imageTag, imageRegistry, id, kv.GetGeneration()) {
			// found backup. UID matches and versions match
			// note, it's possible for a single UID to have multiple backups with
			// different versions
			return false
		}
	}

	return true
}

func shouldBackupRBACObject(kv *v1.KubeVirt, objectMeta *metav1.ObjectMeta) bool {
	curVersion, curImageRegistry, curID := getTargetVersionRegistryID(kv)

	if objectMatchesVersion(objectMeta, curVersion, curImageRegistry, curID, kv.GetGeneration()) {
		// matches current target version already, so doesn't need backup
		return false
	}

	if objectMeta.Annotations == nil {
		return false
	}

	_, ok := objectMeta.Annotations[v1.EphemeralBackupObject]
	if ok {
		// ephemeral backup objects don't need to be backed up because
		// they are the backup
		return false
	}

	return true

}

func needsClusterRoleBindingBackup(kv *v1.KubeVirt, stores util.Stores, crb *rbacv1.ClusterRoleBinding) bool {

	shouldBackup := shouldBackupRBACObject(kv, &crb.ObjectMeta)
	imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&crb.ObjectMeta)
	if !shouldBackup || !ok {
		return false
	}

	// loop through cache and determine if there's an ephemeral backup
	// for this object already
	objects := stores.ClusterRoleBindingCache.List()
	for _, obj := range objects {
		cachedCrb, ok := obj.(*rbacv1.ClusterRoleBinding)

		if !ok ||
			cachedCrb.DeletionTimestamp != nil ||
			crb.Annotations == nil {
			continue
		}

		uid, ok := cachedCrb.Annotations[v1.EphemeralBackupObject]
		if !ok {
			// this is not an ephemeral backup object
			continue
		}

		if uid == string(crb.UID) && objectMatchesVersion(&cachedCrb.ObjectMeta, imageTag, imageRegistry, id, kv.GetGeneration()) {
			// found backup. UID matches and versions match
			// note, it's possible for a single UID to have multiple backups with
			// different versions
			return false
		}
	}

	return true
}
<commit_msg>[virt-operator]: Refactor - one instead of three duplicated functions<commit_after>package apply

import (
	rbacv1 "k8s.io/api/rbac/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/tools/cache"

	v1 "kubevirt.io/client-go/api/v1"
	"kubevirt.io/client-go/log"
)

func (r *Reconciler) backupRBACs() error {

	// Backup existing ClusterRoles
	objects := r.stores.ClusterRoleCache.List()
	for _, obj := range objects {
		cachedCr, ok := obj.(*rbacv1.ClusterRole)
		if !ok || !needsBackup(r.kv, r.stores.ClusterRoleCache, &cachedCr.ObjectMeta) {
			continue
		}
		imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&cachedCr.ObjectMeta)
		if !ok {
			continue
		}

		err := r.backupRBAC(cachedCr.DeepCopy(), cachedCr.Name, string(cachedCr.UID), imageTag, imageRegistry, id, TypeClusterRole)
		if err != nil {
			return err
		}
	}

	// Backup existing ClusterRoleBindings
	objects = r.stores.ClusterRoleBindingCache.List()
	for _, obj := range objects {
		cachedCrb, ok := obj.(*rbacv1.ClusterRoleBinding)
		if !ok || !needsBackup(r.kv, r.stores.ClusterRoleBindingCache, &cachedCrb.ObjectMeta) {
			continue
		}
		imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&cachedCrb.ObjectMeta)
		if !ok {
			continue
		}

		err := r.backupRBAC(cachedCrb.DeepCopy(), cachedCrb.Name, string(cachedCrb.UID), imageTag, imageRegistry, id, TypeClusterRole)
		if err != nil {
			return err
		}
	}

	// Backup existing Roles
	objects = r.stores.RoleCache.List()
	for _, obj := range objects {
		cachedCr, ok := obj.(*rbacv1.Role)
		if !ok || !needsBackup(r.kv, r.stores.RoleCache, &cachedCr.ObjectMeta) {
			continue
		}
		imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&cachedCr.ObjectMeta)
		if !ok {
			continue
		}

		err := r.backupRBAC(cachedCr.DeepCopy(), cachedCr.Name, string(cachedCr.UID), imageTag, imageRegistry, id, TypeClusterRole)
		if err != nil {
			return err
		}
	}

	// Backup existing RoleBindings
	objects = r.stores.RoleBindingCache.List()
	for _, obj := range objects {
		cachedRb, ok := obj.(*rbacv1.RoleBinding)
		if !ok || !needsBackup(r.kv, r.stores.RoleBindingCache, &cachedRb.ObjectMeta) {
			continue
		}
		imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(&cachedRb.ObjectMeta)
		if ok {
			continue
		}

		err := r.backupRBAC(cachedRb.DeepCopy(), cachedRb.Name, string(cachedRb.UID), imageTag, imageRegistry, id, TypeClusterRole)
		if err != nil {
			return err
		}
	}

	return nil
}

func (r *Reconciler) backupRBAC(obj interface{}, name, UID, imageTag, imageRegistry, id string, roleType RoleType) error {
	meta := getRoleMetaObject(obj, roleType)
	*meta = metav1.ObjectMeta{
		GenerateName: name,
	}
	injectOperatorMetadata(r.kv, meta, imageTag, imageRegistry, id, true)
	meta.Annotations[v1.EphemeralBackupObject] = UID

	// Create backup
	createRole := r.getRoleCreateFunction(obj, roleType)
	err := createRole()
	if err != nil {
		return err
	}

	log.Log.V(2).Infof("backup %v %v created", getRoleTypeName(roleType), name)
	return nil
}

func shouldBackupRBACObject(kv *v1.KubeVirt, objectMeta *metav1.ObjectMeta) bool {
	curVersion, curImageRegistry, curID := getTargetVersionRegistryID(kv)

	if objectMatchesVersion(objectMeta, curVersion, curImageRegistry, curID, kv.GetGeneration()) {
		// matches current target version already, so doesn't need backup
		return false
	}

	if objectMeta.Annotations == nil {
		return false
	}

	_, ok := objectMeta.Annotations[v1.EphemeralBackupObject]
	if ok {
		// ephemeral backup objects don't need to be backed up because
		// they are the backup
		return false
	}

	return true

}

func needsBackup(kv *v1.KubeVirt, cache cache.Store, meta *metav1.ObjectMeta) bool {
	shouldBackup := shouldBackupRBACObject(kv, meta)
	imageTag, imageRegistry, id, ok := getInstallStrategyAnnotations(meta)
	if !shouldBackup || !ok {
		return false
	}

	// loop through cache and determine if there's an ephemeral backup
	// for this object already
	objects := cache.List()
	for _, obj := range objects {
		cachedObj, ok := obj.(*metav1.ObjectMeta)

		if !ok ||
			cachedObj.DeletionTimestamp != nil ||
			meta.Annotations == nil {
			continue
		}

		uid, ok := cachedObj.Annotations[v1.EphemeralBackupObject]
		if !ok {
			// this is not an ephemeral backup object
			continue
		}

		if uid == string(meta.UID) && objectMatchesVersion(cachedObj, imageTag, imageRegistry, id, kv.GetGeneration()) {
			// found backup. UID matches and versions match
			// note, it's possible for a single UID to have multiple backups with
			// different versions
			return false
		}
	}

	return true
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"log"
	"time"

	"github.com/armon/go-metrics"
	"github.com/newrelic-forks/memberlist"
	"github.com/newrelic/bosun/catalog"
	"github.com/newrelic/bosun/service"
	"sync"
)

type servicesDelegate struct {
	state             *catalog.ServicesState
	pendingBroadcasts [][]byte
	notifications     chan []byte
	inProcess         bool
	Metadata          NodeMetadata
	sync.Mutex
}

type NodeMetadata struct {
	ClusterName string
	State       string
}

func NewServicesDelegate(state *catalog.ServicesState) *servicesDelegate {
	delegate := servicesDelegate{
		state:             state,
		pendingBroadcasts: make([][]byte, 0),
		notifications:     make(chan []byte, 25),
		inProcess:         false,
		Metadata:          NodeMetadata{ClusterName: "default"},
	}

	return &delegate
}

func (d *servicesDelegate) NodeMeta(limit int) []byte {
	log.Printf("NodeMeta(): %d\n", limit)
	data, err := json.Marshal(d.Metadata)
	if err != nil {
		log.Println("Error encoding Node metadata!")
		data = []byte("{}")
	}
	return data
}

func (d *servicesDelegate) NotifyMsg(message []byte) {
	defer metrics.MeasureSince([]string{"delegate", "NotifyMsg"}, time.Now())

	if len(message) < 1 {
		log.Println("NotifyMsg(): empty")
		return
	}

	log.Printf("NotifyMsg(): %s\n", string(message))

	// TODO don't just send container structs, send message structs
	d.notifications <- message

	// Lazily kick off goroutine
	d.Lock()
	defer d.Unlock()
	if !d.inProcess {
		go func() {
			for message := range d.notifications {
				entry := service.Decode(message)
				if entry == nil {
					log.Printf("NotifyMsg(): error decoding!\n")
					continue
				}
				d.state.AddServiceEntry(*entry)
			}
		}()
		d.inProcess = true
	}
}

func (d *servicesDelegate) GetBroadcasts(overhead, limit int) [][]byte {
	defer metrics.MeasureSince([]string{"delegate", "GetBroadcasts"}, time.Now())
	metrics.SetGauge([]string{"delegate", "pendingBroadcasts"}, float32(len(d.pendingBroadcasts)))

	log.Printf("GetBroadcasts(): %d %d\n", overhead, limit)

	broadcast := make([][]byte, 0, 1)

	select {
	case broadcast = <-d.state.Broadcasts:
	default:
		if len(d.pendingBroadcasts) < 1 {
			return nil
		}
	}

	// Prefer newest messages (TODO what about tombstones?)
	broadcast = append(broadcast, d.pendingBroadcasts...)
	d.pendingBroadcasts = make([][]byte, 0, 1)

	broadcast, leftover := packPacket(broadcast, limit, overhead)
	if len(leftover) > 0 {
		d.pendingBroadcasts = leftover
	}

	if broadcast == nil || len(broadcast) < 1 {
		log.Println("Note: Not enough space to fit any messages or message was nil")
		return nil
	}

	log.Printf("Sending broadcast %d msgs %d 1st length\n",
		len(broadcast), len(broadcast[0]),
	)
	if len(leftover) > 0 {
		log.Printf("Leaving %d messages unsent\n", len(leftover))
	}

	return broadcast
}

func (d *servicesDelegate) LocalState(join bool) []byte {
	log.Printf("LocalState(): %b\n", join)
	return d.state.Encode()
}

func (d *servicesDelegate) MergeRemoteState(buf []byte, join bool) {
	defer metrics.MeasureSince([]string{"delegate", "MergeRemoteState"}, time.Now())

	log.Printf("MergeRemoteState(): %s %b\n", string(buf), join)

	otherState, err := catalog.Decode(buf)
	if err != nil {
		log.Printf("Failed to MergeRemoteState(): %s", err.Error())
		return
	}

	log.Printf("Merging state: %s", otherState.Format(nil))

	d.state.Merge(otherState)
}

func (d *servicesDelegate) NotifyJoin(node *memberlist.Node) {
	log.Printf("NotifyJoin(): %s %s\n", node.Name, string(node.Meta))
}

func (d *servicesDelegate) NotifyLeave(node *memberlist.Node) {
	log.Printf("NotifyLeave(): %s\n", node.Name)
	go d.state.ExpireServer(node.Name)
}

func (d *servicesDelegate) NotifyUpdate(node *memberlist.Node) {
	log.Printf("NotifyUpdate(): %s\n", node.Name)
}

func packPacket(broadcasts [][]byte, limit int, overhead int) (packet [][]byte, leftover [][]byte) {
	total := 0
	leftover = make([][]byte, 0) // So we don't return unallocated buffer
	for _, message := range broadcasts {
		if total+len(message)+overhead < limit {
			packet = append(packet, message)
			total += len(message) + overhead
		} else {
			leftover = append(leftover, message)
		}
	}

	return packet, leftover
}
<commit_msg>Limit pending broadcasts.<commit_after>package main

import (
	"encoding/json"
	"log"
	"time"

	"github.com/armon/go-metrics"
	"github.com/newrelic-forks/memberlist"
	"github.com/newrelic/bosun/catalog"
	"github.com/newrelic/bosun/service"
	"sync"
)

const (
	MAX_PENDING_LENGTH = 100 // Number of messages we can replace into the pending queue
)

type servicesDelegate struct {
	state             *catalog.ServicesState
	pendingBroadcasts [][]byte
	notifications     chan []byte
	inProcess         bool
	Metadata          NodeMetadata
	sync.Mutex
}

type NodeMetadata struct {
	ClusterName string
	State       string
}

func NewServicesDelegate(state *catalog.ServicesState) *servicesDelegate {
	delegate := servicesDelegate{
		state:             state,
		pendingBroadcasts: make([][]byte, 0),
		notifications:     make(chan []byte, 25),
		inProcess:         false,
		Metadata:          NodeMetadata{ClusterName: "default"},
	}

	return &delegate
}

func (d *servicesDelegate) NodeMeta(limit int) []byte {
	log.Printf("NodeMeta(): %d\n", limit)
	data, err := json.Marshal(d.Metadata)
	if err != nil {
		log.Println("Error encoding Node metadata!")
		data = []byte("{}")
	}
	return data
}

func (d *servicesDelegate) NotifyMsg(message []byte) {
	defer metrics.MeasureSince([]string{"delegate", "NotifyMsg"}, time.Now())

	if len(message) < 1 {
		log.Println("NotifyMsg(): empty")
		return
	}

	log.Printf("NotifyMsg(): %s\n", string(message))

	// TODO don't just send container structs, send message structs
	d.notifications <- message

	// Lazily kick off goroutine
	d.Lock()
	defer d.Unlock()
	if !d.inProcess {
		go func() {
			for message := range d.notifications {
				entry := service.Decode(message)
				if entry == nil {
					log.Printf("NotifyMsg(): error decoding!\n")
					continue
				}
				d.state.AddServiceEntry(*entry)
			}
		}()
		d.inProcess = true
	}
}

func (d *servicesDelegate) GetBroadcasts(overhead, limit int) [][]byte {
	defer metrics.MeasureSince([]string{"delegate", "GetBroadcasts"}, time.Now())
	metrics.SetGauge([]string{"delegate", "pendingBroadcasts"}, float32(len(d.pendingBroadcasts)))

	log.Printf("GetBroadcasts(): %d %d\n", overhead, limit)

	broadcast := make([][]byte, 0, 1)

	select {
	case broadcast = <-d.state.Broadcasts:
	default:
		if len(d.pendingBroadcasts) < 1 {
			return nil
		}
	}

	// Prefer newest messages (TODO what about tombstones?)
	broadcast = append(broadcast, d.pendingBroadcasts...)
	d.pendingBroadcasts = make([][]byte, 0, 1)

	broadcast, leftover := packPacket(broadcast, limit, overhead)
	if len(leftover) > 0 {
		// We don't want to store old messages forever, or starve ourselves to death
		if len(leftover) > MAX_PENDING_LENGTH {
			d.pendingBroadcasts = leftover[:MAX_PENDING_LENGTH]
		} else {
			d.pendingBroadcasts = leftover
		}
	}

	if broadcast == nil || len(broadcast) < 1 {
		log.Println("Note: Not enough space to fit any messages or message was nil")
		return nil
	}

	log.Printf("Sending broadcast %d msgs %d 1st length\n",
		len(broadcast), len(broadcast[0]),
	)
	if len(leftover) > 0 {
		log.Printf("Leaving %d messages unsent\n", len(leftover))
	}

	return broadcast
}

func (d *servicesDelegate) LocalState(join bool) []byte {
	log.Printf("LocalState(): %b\n", join)
	return d.state.Encode()
}

func (d *servicesDelegate) MergeRemoteState(buf []byte, join bool) {
	defer metrics.MeasureSince([]string{"delegate", "MergeRemoteState"}, time.Now())

	log.Printf("MergeRemoteState(): %s %b\n", string(buf), join)

	otherState, err := catalog.Decode(buf)
	if err != nil {
		log.Printf("Failed to MergeRemoteState(): %s", err.Error())
		return
	}

	log.Printf("Merging state: %s", otherState.Format(nil))

	d.state.Merge(otherState)
}

func (d *servicesDelegate) NotifyJoin(node *memberlist.Node) {
	log.Printf("NotifyJoin(): %s %s\n", node.Name, string(node.Meta))
}

func (d *servicesDelegate) NotifyLeave(node *memberlist.Node) {
	log.Printf("NotifyLeave(): %s\n", node.Name)
	go d.state.ExpireServer(node.Name)
}

func (d *servicesDelegate) NotifyUpdate(node *memberlist.Node) {
	log.Printf("NotifyUpdate(): %s\n", node.Name)
}

func packPacket(broadcasts [][]byte, limit int, overhead int) (packet [][]byte, leftover [][]byte) {
	total := 0
	leftover = make([][]byte, 0) // So we don't return unallocated buffer
	for _, message := range broadcasts {
		if total+len(message)+overhead < limit {
			packet = append(packet, message)
			total += len(message) + overhead
		} else {
			leftover = append(leftover, message)
		}
	}

	return packet, leftover
}
<|endoftext|>


<commit_before>package dsmr4p1

import (
	"bytes"
	"errors"
	"strings"
)

// Telegram holds the a P1 telegram. It is essentially a slice of bytes.
type Telegram []byte

// Identifier returns the identifier in the telegram.
func (t Telegram) Identifier() string {
	// According to the documentation, the telegram starts with:
	// "/XXXZ Ident CR LF CR LF", followed by the data.
	i := bytes.Index(t, []byte("\r\n\r\n"))
	return string(t[5:i])
}

// Parse attempts to parse the telegram. It returns a map of strings to string
// slices. The keys in the map are the ID-codes, the strings in the slice are
// are the value between brackets for that ID-code.
func (t Telegram) Parse() (map[string][]string, error) {
	// Parse the telegram in a relatively naive way. Of course this
	// is not properly langsec approved :)

	lines := strings.Split(string(t), "\r\n")

	if len(lines) < 2 {
		return nil, errors.New("Parse error: unexpected number of lines in telegram.")
	}

	// Some additional checks
	if lines[0][0] != '/' {
		return nil, errors.New("Expected '/' missing in first line of telegram.")
	}
	if len(lines[1]) != 0 {
		return nil, errors.New("Missing separating new line (CR+LF) between identifier and data in telegram.")
	}

	result := make(map[string][]string)
	// Iterate over the lines and try to parse the data. The first two lines can
	// be skipped because they should contain the identifier (see Identifier())
	// and a new-line.  The last line is skipped because it should only contain an
	// exclamation mark.
	for i, l := range lines[2 : len(lines)-1] {
		idCodeEnd := strings.Index(l, "(")
		if idCodeEnd == -1 {
			return nil, errors.New("Expected '(', not found on line" + string(i))
		}

		idCode := l[:idCodeEnd]

		// The rest of the line is a number of values in round brackets "()".
		// Let's use a simple split on ")(" to get those.
		parts := strings.Split(l[idCodeEnd+1:len(l)-1], ")(")
		result[idCode] = parts
	}

	return result, nil
}
<commit_msg>Cleanup telegram.go<commit_after>package dsmr4p1

import (
	"bytes"
	"errors"
	"strconv"
	"strings"
)

// Telegram holds the a P1 telegram. It is essentially a slice of bytes.
type Telegram []byte

// Identifier returns the identifier in the telegram.
func (t Telegram) Identifier() string {
	// According to the documentation, the telegram starts with:
	// "/XXXZ Ident CR LF CR LF", followed by the data.
	i := bytes.Index(t, []byte("\r\n\r\n"))
	return string(t[5:i])
}

// Parse attempts to parse the telegram. It returns a map of strings to string
// slices. The keys in the map are the ID-codes, the strings in the slice are
// are the value between brackets for that ID-code.
func (t Telegram) Parse() (map[string][]string, error) {
	// Parse the telegram in a relatively naive way. Of course this
	// is not properly langsec approved :)

	lines := strings.Split(string(t), "\r\n")

	if len(lines) < 2 {
		return nil, errors.New("parse error: unexpected number of lines in telegram")
	}

	// Some additional checks
	if lines[0][0] != '/' {
		return nil, errors.New("expected '/' missing in first line of telegram")
	}
	if len(lines[1]) != 0 {
		return nil, errors.New("missing separating new line (CR+LF) between identifier and data in telegram")
	}

	result := make(map[string][]string)
	// Iterate over the lines and try to parse the data. The first two lines can
	// be skipped because they should contain the identifier (see Identifier())
	// and a new-line.  The last line is skipped because it should only contain an
	// exclamation mark.
	for i, l := range lines[2 : len(lines)-1] {
		idCodeEnd := strings.Index(l, "(")
		if idCodeEnd == -1 {
			return nil, errors.New("Expected '(', not found on line" + strconv.Itoa(i))
		}

		idCode := l[:idCodeEnd]

		// The rest of the line is a number of values in round brackets "()".
		// Let's use a simple split on ")(" to get those.
		parts := strings.Split(l[idCodeEnd+1:len(l)-1], ")(")
		result[idCode] = parts
	}

	return result, nil
}
<|endoftext|>


<commit_before>package brands

import (
	"encoding/json"
	"fmt"
	"github.com/Financial-Times/neo-utils-go/neoutils"
	log "github.com/Sirupsen/logrus"
	"github.com/jmcvetta/neoism"
)

//service maintains info about runners and index managers
type service struct {
	cypherRunner neoutils.CypherRunner
	indexManager neoutils.IndexManager
}

// NewCypherBrandsService provides functions for create, update, delete operations on brands in Neo4j,
// plus other utility functions needed for a service
func NewCypherBrandsService(cypherRunner neoutils.CypherRunner, indexManager neoutils.IndexManager) service {
	return service{cypherRunner, indexManager}
}

//Initialise the driver
func (s service) Initialise() error {
	entities := map[string]string{
		"Thing":   "uuid",
		"Concept": "uuid",
		"Brand":   "uuid",
	}
	if err := neoutils.EnsureConstraints(s.indexManager, entities); err != nil {
		return err
	}
	if err := neoutils.EnsureIndexes(s.indexManager, entities); err != nil {
		return err
	}
	return nil
}

func (s service) Read(uuid string) (interface{}, bool, error) {
	results := []struct {
		Brand
	}{}
	query := &neoism.CypherQuery{
		Statement: `
                        MATCH (n:Brand {uuid:{uuid}})
                        OPTIONAL MATCH (n:Brand {uuid:{uuid}})-[:HAS_PARENT]->(p:Thing)
                        OPTIONAL MATCH (n)<-[:IDENTIFIES]-(i:Identifier)
                        RETURN n.uuid AS uuid, n.prefLabel AS prefLabel,
                                n.strapline AS strapline, p.uuid as parentUUID,
                                n.descriptionXML AS descriptionXML,
                                n.description AS description, n.imageUrl AS _imageUrl,
                                collect({authority:i.authority, identifierValue:i.value}) as identifiers
                                `,
		Parameters: map[string]interface{}{
			"uuid": uuid,
		},
		Result: &results,
	}
	err := s.cypherRunner.CypherBatch([]*neoism.CypherQuery{query})
	log.Infof("Read brand : %s returned %+v\n", uuid, results)
	if err != nil {
		return Brand{}, false, err
	}
	if len(results) == 0 {
		return Brand{}, false, nil
	}
	return results[0].Brand, true, nil
}

func (s service) Write(thing interface{}) error {
	brand := thing.(Brand)
	brandProps := map[string]string{
		"uuid":           brand.UUID,
		"prefLabel":      brand.PrefLabel,
		"strapline":      brand.Strapline,
		"descriptionXML": brand.DescriptionXML,
		"description":    brand.Description,
		"imageUrl":       brand.ImageURL,
	}
	stmt := `
                OPTIONAL MATCH (:Brand {uuid:{uuid}})-[r:HAS_PARENT]->(:Brand)
                DELETE r
                MERGE (n:Thing {uuid: {uuid}})
                SET n:Brand
                SET n:Concept
                SET n={props}
                `
	params := neoism.Props{
		"uuid":  brand.UUID,
		"props": brandProps,
	}
	parentUUID := brand.ParentUUID
	if parentUUID != "" {
		stmt += `
                        MERGE (p:Thing {uuid:{parentUUID}})
                        MERGE (n)-[:HAS_PARENT]->(p)
                        `
		params["parentUUID"] = brand.ParentUUID
	}

	deleteIdentifiers := &neoism.CypherQuery{
		Statement: `MATCH (t:Thing {uuid:{uuid}})
                                OPTIONAL MATCH (i:Identifier)-[ir:IDENTIFIES]->(t)
                                DELETE ir, i`,
		Parameters: map[string]interface{}{
			"uuid": brand.UUID,
		},
	}

	writeQuery := &neoism.CypherQuery{
		Statement:  stmt,
		Parameters: params,
	}

	queries := []*neoism.CypherQuery{deleteIdentifiers, writeQuery}

	for _, identifier := range brand.Identifiers {
		queries = append(queries, identifierMerge(identifier, brand.UUID))
	}
	return s.cypherRunner.CypherBatch(queries)

}

const (
	fsAuthority  = "http://api.ft.com/system/FACTSET-PPL"
	tmeAuthority = "http://api.ft.com/system/FT-TME"
)

var identifierLabels = map[string]string{
	fsAuthority:  "FactsetIdentifier",
	tmeAuthority: "TMEIdentifier",
}

func identifierMerge(identifier identifier, uuid string) *neoism.CypherQuery {
	statementTemplate := fmt.Sprintf(`MERGE (o:Thing {uuid:{uuid}})
                                          MERGE (i:Identifier {value:{value} , authority:{authority}})
                                          MERGE (o)<-[:IDENTIFIES]-(i)
                                          set i:%s`, identifierLabels[identifier.Authority])

	query := &neoism.CypherQuery{
		Statement: statementTemplate,
		Parameters: map[string]interface{}{
			"uuid":      uuid,
			"value":     identifier.IdentifierValue,
			"authority": identifier.Authority,
		},
	}
	return query
}

func (s service) Delete(uuid string) (bool, error) {
	clearNode := &neoism.CypherQuery{
		Statement: `
			MATCH (n:Thing {uuid: {uuid}})
			REMOVE n:Brand
			SET n={props}
		`,
		Parameters: neoism.Props{
			"uuid": uuid,
			"props": neoism.Props{
				"uuid": uuid,
			},
		},
		IncludeStats: true,
	}

	removeNodeIfUnused := &neoism.CypherQuery{
		Statement: `
			MATCH (p:Thing {uuid: {uuid}})
			OPTIONAL MATCH (p)-[a]-(x)
			WITH p, count(a) AS relCount
			WHERE relCount = 0
			DELETE p
		`,
		Parameters: neoism.Props{
			"uuid": uuid,
		},
	}

	err := s.cypherRunner.CypherBatch([]*neoism.CypherQuery{clearNode, removeNodeIfUnused})

	s1, err := clearNode.Stats()
	if err != nil {
		return false, err
	}

	var deleted bool
	if s1.ContainsUpdates && s1.LabelsRemoved > 0 {
		deleted = true
	}

	return deleted, err
}

func (s service) DecodeJSON(dec *json.Decoder) (interface{}, string, error) {
	brand := Brand{}
	err := dec.Decode(&brand)
	return brand, brand.UUID, err
}

func (s service) Check() error {
	return neoutils.Check(s.cypherRunner)
}

func (s service) Count() (int, error) {

	results := []struct {
		Count int `json:"c"`
	}{}

	query := &neoism.CypherQuery{
		Statement: `MATCH (n:Brand) return count(n) as c`,
		Result:    &results,
	}

	err := s.cypherRunner.CypherBatch([]*neoism.CypherQuery{query})

	if err != nil {
		return 0, err
	}

	return results[0].Count, nil
}
<commit_msg>Check for links to Identities and remove then<commit_after>package brands

import (
	"encoding/json"
	"fmt"
	"github.com/Financial-Times/neo-utils-go/neoutils"
	log "github.com/Sirupsen/logrus"
	"github.com/jmcvetta/neoism"
)

//service maintains info about runners and index managers
type service struct {
	cypherRunner neoutils.CypherRunner
	indexManager neoutils.IndexManager
}

// NewCypherBrandsService provides functions for create, update, delete operations on brands in Neo4j,
// plus other utility functions needed for a service
func NewCypherBrandsService(cypherRunner neoutils.CypherRunner, indexManager neoutils.IndexManager) service {
	return service{cypherRunner, indexManager}
}

//Initialise the driver
func (s service) Initialise() error {
	entities := map[string]string{
		"Thing":   "uuid",
		"Concept": "uuid",
		"Brand":   "uuid",
	}
	if err := neoutils.EnsureConstraints(s.indexManager, entities); err != nil {
		return err
	}
	if err := neoutils.EnsureIndexes(s.indexManager, entities); err != nil {
		return err
	}
	return nil
}

func (s service) Read(uuid string) (interface{}, bool, error) {
	results := []struct {
		Brand
	}{}
	query := &neoism.CypherQuery{
		Statement: `
                        MATCH (n:Brand {uuid:{uuid}})
                        OPTIONAL MATCH (n:Brand {uuid:{uuid}})-[:HAS_PARENT]->(p:Thing)
                        OPTIONAL MATCH (n)<-[:IDENTIFIES]-(i:Identifier)
                        RETURN n.uuid AS uuid, n.prefLabel AS prefLabel,
                                n.strapline AS strapline, p.uuid as parentUUID,
                                n.descriptionXML AS descriptionXML,
                                n.description AS description, n.imageUrl AS _imageUrl,
                                collect({authority:i.authority, identifierValue:i.value}) as identifiers
                                `,
		Parameters: map[string]interface{}{
			"uuid": uuid,
		},
		Result: &results,
	}
	err := s.cypherRunner.CypherBatch([]*neoism.CypherQuery{query})
	log.Infof("Read brand : %s returned %+v\n", uuid, results)
	if err != nil {
		return Brand{}, false, err
	}
	if len(results) == 0 {
		return Brand{}, false, nil
	}
	return results[0].Brand, true, nil
}

func (s service) Write(thing interface{}) error {
	brand := thing.(Brand)
	brandProps := map[string]string{
		"uuid":           brand.UUID,
		"prefLabel":      brand.PrefLabel,
		"strapline":      brand.Strapline,
		"descriptionXML": brand.DescriptionXML,
		"description":    brand.Description,
		"imageUrl":       brand.ImageURL,
	}
	stmt := `
                OPTIONAL MATCH (:Brand {uuid:{uuid}})-[r:HAS_PARENT]->(:Brand)
                DELETE r
                MERGE (n:Thing {uuid: {uuid}})
                SET n:Brand
                SET n:Concept
                SET n={props}
                `
	params := neoism.Props{
		"uuid":  brand.UUID,
		"props": brandProps,
	}
	parentUUID := brand.ParentUUID
	if parentUUID != "" {
		stmt += `
                        MERGE (p:Thing {uuid:{parentUUID}})
                        MERGE (n)-[:HAS_PARENT]->(p)
                        `
		params["parentUUID"] = brand.ParentUUID
	}

	deleteIdentifiers := &neoism.CypherQuery{
		Statement: `MATCH (t:Thing {uuid:{uuid}})
                                OPTIONAL MATCH (i:Identifier)-[ir:IDENTIFIES]->(t)
                                DELETE ir, i`,
		Parameters: map[string]interface{}{
			"uuid": brand.UUID,
		},
	}

	writeQuery := &neoism.CypherQuery{
		Statement:  stmt,
		Parameters: params,
	}

	queries := []*neoism.CypherQuery{deleteIdentifiers, writeQuery}

	for _, identifier := range brand.Identifiers {
		queries = append(queries, identifierMerge(identifier, brand.UUID))
	}
	return s.cypherRunner.CypherBatch(queries)

}

const (
	fsAuthority  = "http://api.ft.com/system/FACTSET-PPL"
	tmeAuthority = "http://api.ft.com/system/FT-TME"
)

var identifierLabels = map[string]string{
	fsAuthority:  "FactsetIdentifier",
	tmeAuthority: "TMEIdentifier",
}

func identifierMerge(identifier identifier, uuid string) *neoism.CypherQuery {
	statementTemplate := fmt.Sprintf(`MERGE (o:Thing {uuid:{uuid}})
                                          MERGE (i:Identifier {value:{value} , authority:{authority}})
                                          MERGE (o)<-[:IDENTIFIES]-(i)
                                          set i:%s`, identifierLabels[identifier.Authority])

	query := &neoism.CypherQuery{
		Statement: statementTemplate,
		Parameters: map[string]interface{}{
			"uuid":      uuid,
			"value":     identifier.IdentifierValue,
			"authority": identifier.Authority,
		},
	}
	return query
}

func (s service) Delete(uuid string) (bool, error) {
	deleteIdentifiers := &neoism.CypherQuery{
		Statement: `MATCH (t:Thing {uuid:{uuid}})
                                OPTIONAL MATCH (i:Identifier)-[ir:IDENTIFIES]->(t)
                                DELETE ir
                                WITH i
                                MATCH (i)-[ir2:IDENTIFIES]->(:Thing)
                                WITH i, count(ir2) as c
                                WHERE c = 0
                                DELETE i
                                `,
		Parameters: map[string]interface{}{
			"uuid": uuid,
		},
	}

	clearNode := &neoism.CypherQuery{
		Statement: `
			MATCH (n:Thing {uuid: {uuid}})
			REMOVE n:Brand
			SET n={props}
		`,
		Parameters: neoism.Props{
			"uuid": uuid,
			"props": neoism.Props{
				"uuid": uuid,
			},
		},
		IncludeStats: true,
	}

	removeNodeIfUnused := &neoism.CypherQuery{
		Statement: `
			MATCH (p:Thing {uuid: {uuid}})
			OPTIONAL MATCH (p)-[a]-(x)
			WITH p, count(a) AS relCount
			WHERE relCount = 0
			DELETE p
		`,
		Parameters: neoism.Props{
			"uuid": uuid,
		},
	}

	err := s.cypherRunner.CypherBatch([]*neoism.CypherQuery{deleteIdentifiers, clearNode, removeNodeIfUnused})

	s1, err := clearNode.Stats()
	if err != nil {
		return false, err
	}

	var deleted bool
	if s1.ContainsUpdates && s1.LabelsRemoved > 0 {
		deleted = true
	}

	return deleted, err
}

func (s service) DecodeJSON(dec *json.Decoder) (interface{}, string, error) {
	brand := Brand{}
	err := dec.Decode(&brand)
	return brand, brand.UUID, err
}

func (s service) Check() error {
	return neoutils.Check(s.cypherRunner)
}

func (s service) Count() (int, error) {

	results := []struct {
		Count int `json:"c"`
	}{}

	query := &neoism.CypherQuery{
		Statement: `MATCH (n:Brand) return count(n) as c`,
		Result:    &results,
	}

	err := s.cypherRunner.CypherBatch([]*neoism.CypherQuery{query})

	if err != nil {
		return 0, err
	}

	return results[0].Count, nil
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/didip/tollbooth"
	"net/http"
	"path/filepath"
	"sync"
	"time"

	log "github.com/sirupsen/logrus"
	"github.com/xyproto/pinterface"
	"github.com/yuin/gopher-lua"
)

// Make functions related to handling HTTP requests available to Lua scripts
func exportLuaHandlerFunctions(L *lua.LState, filename string, perm pinterface.IPermissions, luapool *lStatePool, cache *FileCache, mux *http.ServeMux, addDomain bool, httpStatus *FutureStatus, theme string, pongomutex *sync.RWMutex) {

	L.SetGlobal("handle", L.NewFunction(func(L *lua.LState) int {
		handlePath := L.ToString(1)
		handleFunc := L.ToFunction(2)

		wrappedHandleFunc := func(w http.ResponseWriter, req *http.Request) {

			L2 := luapool.Get()
			defer luapool.Put(L2)

			// Set up a new Lua state with the current http.ResponseWriter and *http.Request
			exportCommonFunctions(w, req, filename, perm, L2, luapool, nil, cache, httpStatus, pongomutex)

			// Then run the given Lua function
			L2.Push(handleFunc)
			if err := L2.PCall(0, lua.MultRet, nil); err != nil {
				// Non-fatal error
				log.Error("Handler for "+handlePath+" failed:", err)
			}
		}

		// Handle requests differently depending on if rate limiting is enabled or not
		if disableRateLimiting {
			mux.HandleFunc(handlePath, wrappedHandleFunc)
		} else {
			limiter := tollbooth.NewLimiter(limitRequests, time.Second)
			limiter.MessageContentType = "text/html; charset=utf-8"
			limiter.Message = easyPage("Rate-limit exceeded", "
You have reached the maximum request limit.
", theme)
			mux.Handle(handlePath, tollbooth.LimitFuncHandler(limiter, wrappedHandleFunc))
		}

		return 0 // number of results
	}))

	L.SetGlobal("servedir", L.NewFunction(func(L *lua.LState) int {
		handlePath := L.ToString(1) // serve as (ie. "/")
		rootdir := L.ToString(2)    // filesystem directory (ie. "./public")
		rootdir = filepath.Join(filepath.Dir(filename), rootdir)

		registerHandlers(mux, handlePath, rootdir, perm, luapool, cache, addDomain, theme, pongomutex)

		return 0 // number of results
	}))

}
<commit_msg>Add mutex for the Lua handler<commit_after>package main

import (
	"github.com/didip/tollbooth"
	"net/http"
	"path/filepath"
	"sync"
	"time"

	log "github.com/sirupsen/logrus"
	"github.com/xyproto/pinterface"
	"github.com/yuin/gopher-lua"
)

// Make functions related to handling HTTP requests available to Lua scripts
func exportLuaHandlerFunctions(L *lua.LState, filename string, perm pinterface.IPermissions, luapool *lStatePool, cache *FileCache, mux *http.ServeMux, addDomain bool, httpStatus *FutureStatus, theme string, pongomutex *sync.RWMutex) {

	luahandlermutex := &sync.RWMutex{}

	L.SetGlobal("handle", L.NewFunction(func(L *lua.LState) int {
		handlePath := L.ToString(1)
		handleFunc := L.ToFunction(2)

		wrappedHandleFunc := func(w http.ResponseWriter, req *http.Request) {

			L2 := luapool.Get()
			defer luapool.Put(L2)

			luahandlermutex.Lock()
			defer luahandlermutex.Unlock()

			// Set up a new Lua state with the current http.ResponseWriter and *http.Request
			exportCommonFunctions(w, req, filename, perm, L2, luapool, nil, cache, httpStatus, pongomutex)

			// Then run the given Lua function
			L2.Push(handleFunc)
			if err := L2.PCall(0, lua.MultRet, nil); err != nil {
				// Non-fatal error
				log.Error("Handler for "+handlePath+" failed:", err)
			}
		}

		// Handle requests differently depending on if rate limiting is enabled or not
		if disableRateLimiting {
			mux.HandleFunc(handlePath, wrappedHandleFunc)
		} else {
			limiter := tollbooth.NewLimiter(limitRequests, time.Second)
			limiter.MessageContentType = "text/html; charset=utf-8"
			limiter.Message = easyPage("Rate-limit exceeded", "
You have reached the maximum request limit.
", theme)
			mux.Handle(handlePath, tollbooth.LimitFuncHandler(limiter, wrappedHandleFunc))
		}

		return 0 // number of results
	}))

	L.SetGlobal("servedir", L.NewFunction(func(L *lua.LState) int {
		handlePath := L.ToString(1) // serve as (ie. "/")
		rootdir := L.ToString(2)    // filesystem directory (ie. "./public")
		rootdir = filepath.Join(filepath.Dir(filename), rootdir)

		registerHandlers(mux, handlePath, rootdir, perm, luapool, cache, addDomain, theme, pongomutex)

		return 0 // number of results
	}))

}
<|endoftext|>