<commit_before>/*
   Copyright The containerd Authors.

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

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

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

package v2

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

	"github.com/containerd/containerd/identifiers"
	"github.com/containerd/containerd/mount"
	"github.com/containerd/containerd/namespaces"
	"github.com/containerd/typeurl"
	"github.com/opencontainers/runtime-spec/specs-go"
)

const configFilename = "config.json"

// LoadBundle loads an existing bundle from disk
func LoadBundle(ctx context.Context, root, id string) (*Bundle, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}
	return &Bundle{
		ID:        id,
		Path:      filepath.Join(root, ns, id),
		Namespace: ns,
	}, nil
}

// NewBundle returns a new bundle on disk
func NewBundle(ctx context.Context, root, state, id string, spec typeurl.Any) (b *Bundle, err error) {
	if err := identifiers.Validate(id); err != nil {
		return nil, fmt.Errorf("invalid task id %s: %w", id, err)
	}

	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}
	work := filepath.Join(root, ns, id)
	b = &Bundle{
		ID:        id,
		Path:      filepath.Join(state, ns, id),
		Namespace: ns,
	}
	var paths []string
	defer func() {
		if err != nil {
			for _, d := range paths {
				os.RemoveAll(d)
			}
		}
	}()
	// create state directory for the bundle
	if err := os.MkdirAll(filepath.Dir(b.Path), 0711); err != nil {
		return nil, err
	}
	if err := os.Mkdir(b.Path, 0700); err != nil {
		return nil, err
	}
	if typeurl.Is(spec, &specs.Spec{}) {
		if err := prepareBundleDirectoryPermissions(b.Path, spec.GetValue()); err != nil {
			return nil, err
		}
	}
	paths = append(paths, b.Path)
	// create working directory for the bundle
	if err := os.MkdirAll(filepath.Dir(work), 0711); err != nil {
		return nil, err
	}
	rootfs := filepath.Join(b.Path, "rootfs")
	if err := os.MkdirAll(rootfs, 0711); err != nil {
		return nil, err
	}
	paths = append(paths, rootfs)
	if err := os.Mkdir(work, 0711); err != nil {
		if !os.IsExist(err) {
			return nil, err
		}
		os.RemoveAll(work)
		if err := os.Mkdir(work, 0711); err != nil {
			return nil, err
		}
	}
	paths = append(paths, work)
	// symlink workdir
	if err := os.Symlink(work, filepath.Join(b.Path, "work")); err != nil {
		return nil, err
	}
	if spec := spec.GetValue(); spec != nil {
		// write the spec to the bundle
		err = os.WriteFile(filepath.Join(b.Path, configFilename), spec, 0666)
		if err != nil {
			return nil, fmt.Errorf("failed to write %s", configFilename)
		}
	}
	return b, nil
}

// Bundle represents an OCI bundle
type Bundle struct {
	// ID of the bundle
	ID string
	// Path to the bundle
	Path string
	// Namespace of the bundle
	Namespace string
}

// Delete a bundle atomically
func (b *Bundle) Delete() error {
	work, werr := os.Readlink(filepath.Join(b.Path, "work"))
	rootfs := filepath.Join(b.Path, "rootfs")
	if err := mount.UnmountAll(rootfs, 0); err != nil {
		return fmt.Errorf("unmount rootfs %s: %w", rootfs, err)
	}
	if err := os.Remove(rootfs); err != nil && !os.IsNotExist(err) {
		return fmt.Errorf("failed to remove bundle rootfs: %w", err)
	}
	err := atomicDelete(b.Path)
	if err == nil {
		if werr == nil {
			return atomicDelete(work)
		}
		return nil
	}
	// error removing the bundle path; still attempt removing work dir
	var err2 error
	if werr == nil {
		err2 = atomicDelete(work)
		if err2 == nil {
			return err
		}
	}
	return fmt.Errorf("failed to remove both bundle and workdir locations: %v: %w", err2, err)
}

// atomicDelete renames the path to a hidden file before removal
func atomicDelete(path string) error {
	// create a hidden dir for an atomic removal
	atomicPath := filepath.Join(filepath.Dir(path), fmt.Sprintf(".%s", filepath.Base(path)))
	if err := os.Rename(path, atomicPath); err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	return os.RemoveAll(atomicPath)
}
<commit_msg>Don't unmount on Darwin when deleting bundle<commit_after>/*
   Copyright The containerd Authors.

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

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

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

package v2

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

	"github.com/containerd/containerd/identifiers"
	"github.com/containerd/containerd/mount"
	"github.com/containerd/containerd/namespaces"
	"github.com/containerd/typeurl"
	"github.com/opencontainers/runtime-spec/specs-go"
)

const configFilename = "config.json"

// LoadBundle loads an existing bundle from disk
func LoadBundle(ctx context.Context, root, id string) (*Bundle, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}
	return &Bundle{
		ID:        id,
		Path:      filepath.Join(root, ns, id),
		Namespace: ns,
	}, nil
}

// NewBundle returns a new bundle on disk
func NewBundle(ctx context.Context, root, state, id string, spec typeurl.Any) (b *Bundle, err error) {
	if err := identifiers.Validate(id); err != nil {
		return nil, fmt.Errorf("invalid task id %s: %w", id, err)
	}

	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}
	work := filepath.Join(root, ns, id)
	b = &Bundle{
		ID:        id,
		Path:      filepath.Join(state, ns, id),
		Namespace: ns,
	}
	var paths []string
	defer func() {
		if err != nil {
			for _, d := range paths {
				os.RemoveAll(d)
			}
		}
	}()
	// create state directory for the bundle
	if err := os.MkdirAll(filepath.Dir(b.Path), 0711); err != nil {
		return nil, err
	}
	if err := os.Mkdir(b.Path, 0700); err != nil {
		return nil, err
	}
	if typeurl.Is(spec, &specs.Spec{}) {
		if err := prepareBundleDirectoryPermissions(b.Path, spec.GetValue()); err != nil {
			return nil, err
		}
	}
	paths = append(paths, b.Path)
	// create working directory for the bundle
	if err := os.MkdirAll(filepath.Dir(work), 0711); err != nil {
		return nil, err
	}
	rootfs := filepath.Join(b.Path, "rootfs")
	if err := os.MkdirAll(rootfs, 0711); err != nil {
		return nil, err
	}
	paths = append(paths, rootfs)
	if err := os.Mkdir(work, 0711); err != nil {
		if !os.IsExist(err) {
			return nil, err
		}
		os.RemoveAll(work)
		if err := os.Mkdir(work, 0711); err != nil {
			return nil, err
		}
	}
	paths = append(paths, work)
	// symlink workdir
	if err := os.Symlink(work, filepath.Join(b.Path, "work")); err != nil {
		return nil, err
	}
	if spec := spec.GetValue(); spec != nil {
		// write the spec to the bundle
		err = os.WriteFile(filepath.Join(b.Path, configFilename), spec, 0666)
		if err != nil {
			return nil, fmt.Errorf("failed to write %s", configFilename)
		}
	}
	return b, nil
}

// Bundle represents an OCI bundle
type Bundle struct {
	// ID of the bundle
	ID string
	// Path to the bundle
	Path string
	// Namespace of the bundle
	Namespace string
}

// Delete a bundle atomically
func (b *Bundle) Delete() error {
	work, werr := os.Readlink(filepath.Join(b.Path, "work"))
	rootfs := filepath.Join(b.Path, "rootfs")
	if runtime.GOOS != "darwin" {
		if err := mount.UnmountAll(rootfs, 0); err != nil {
			return fmt.Errorf("unmount rootfs %s: %w", rootfs, err)
		}
	}
	if err := os.Remove(rootfs); err != nil && !os.IsNotExist(err) {
		return fmt.Errorf("failed to remove bundle rootfs: %w", err)
	}
	err := atomicDelete(b.Path)
	if err == nil {
		if werr == nil {
			return atomicDelete(work)
		}
		return nil
	}
	// error removing the bundle path; still attempt removing work dir
	var err2 error
	if werr == nil {
		err2 = atomicDelete(work)
		if err2 == nil {
			return err
		}
	}
	return fmt.Errorf("failed to remove both bundle and workdir locations: %v: %w", err2, err)
}

// atomicDelete renames the path to a hidden file before removal
func atomicDelete(path string) error {
	// create a hidden dir for an atomic removal
	atomicPath := filepath.Join(filepath.Dir(path), fmt.Sprintf(".%s", filepath.Base(path)))
	if err := os.Rename(path, atomicPath); err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	return os.RemoveAll(atomicPath)
}
<|endoftext|>


<commit_before>// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package licensecheck

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"math"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
)

func TestTestdata(t *testing.T) {
	files, err := filepath.Glob("testdata/*")
	if err != nil {
		t.Fatal(err)
	}
	if len(files) == 0 {
		t.Fatalf("no testdata files found")
	}

	for _, file := range files {
		name := filepath.Base(file)
		if name == "README" {
			continue
		}
		t.Run(file, func(t *testing.T) {
			t.Parallel() // faster and tests for races in parallel usage
			data, err := ioutil.ReadFile(file)
			if err != nil {
				t.Fatal(err)
			}

			// See testdata/README for definition of test data file.
			// Header ends at blank line.
			i := bytes.Index(data, []byte("\n\n"))
			if i < 0 {
				t.Fatalf("invalid test data file: no blank line terminating header")
			}
			hdr, data := strings.Split(string(data[:i]), "\n"), data[i+2:]

			lineno := 1
			// Skip leading comment lines.
			for len(hdr) > 0 && strings.HasPrefix(hdr[0], "#") {
				hdr = hdr[1:]
				lineno++
			}

			if len(hdr) > 0 && strings.HasPrefix(hdr[0], "set ") {
				t.Fatalf("%s:%d: set not implemented", file, lineno)
				hdr = hdr[1:]
				lineno++
			}
			if len(hdr) < 1 {
				t.Fatalf("header too short")
			}

			linenoStart := lineno
			var want Coverage
			want.Percent, err = parsePercent(hdr[0])
			if err != nil {
				t.Fatalf("%s:%d: parsing want.Percent: %v", file, lineno, err)
			}
			hdr = hdr[1:]
			lineno++
			want.Match = make([]Match, len(hdr))
			for i, line := range hdr {
				f := strings.Fields(line)
				if len(f) != 3 && len(f) != 4 {
					t.Fatalf("%s:%d: bad match field count", file, lineno)
				}
				m := &want.Match[i]
				m.Name = f[0]
				m.Percent, err = parsePercent(f[1])
				if err != nil {
					t.Fatalf("%s:%d: parsing want.Match[%d].Percent: %v", file, lineno, i, err)
				}
				m.Start, m.End, err = parseRange(f[2], len(data))
				if err != nil {
					t.Fatalf("%s:%d: parsing want.Match[%d].Start,End: %v", file, lineno, i, err)
				}
				if len(f) == 4 {
					if f[3] != "URL" {
						t.Fatalf("%s:%d: field 3 should not be omitted or should be 'URL'", file, lineno)
					}
					m.IsURL = true
				}
				lineno++
			}
			linenoEnd := lineno

			cov, ok := Cover(data, Options{})
			if (len(cov.Match) > 0) != ok {
				t.Errorf("len(cov.Match)=%d but ok=%v, want %v", len(cov.Match), ok, !ok)
			}

			mismatch := false
			var buf bytes.Buffer
			if !matchPercent(cov.Percent, want.Percent) {
				fmt.Fprintf(&buf, "- %.1f%%\n+ %.1f%%\n", want.Percent, cov.Percent)
				mismatch = true
			} else {
				fmt.Fprintf(&buf, "  %.1f%%\n", cov.Percent)
			}

			covm, wantm := cov.Match, want.Match
			for len(covm) > 0 || len(wantm) > 0 {
				switch {
				case len(covm) > 0 && (len(wantm) == 0 || covm[0].End < wantm[0].Start):
					fmt.Fprintf(&buf, "+ %v\n", fmtMatch(covm[0], len(data)))
					covm = covm[1:]
					mismatch = true

				case len(covm) > 0 && len(wantm) > 0 && matchMatch(covm[0], wantm[0]):
					fmt.Fprintf(&buf, "  %v\n", fmtMatch(covm[0], len(data)))
					covm = covm[1:]
					wantm = wantm[1:]

				default:
					fmt.Fprintf(&buf, "- %v\n", fmtMatch(wantm[0], len(data)))
					wantm = wantm[1:]
					mismatch = true
				}
			}
			if mismatch {
				t.Errorf("%s:%d,%d: diff -want +have:\n%s", file, linenoStart, linenoEnd, buf.Bytes())
			}
		})
	}
}

// fmtMatch formats the match m for printing.
func fmtMatch(m Match, end int) string {
	// Special case for EOF end position.
	var hi string
	if m.End == end {
		hi = "$"
	} else {
		hi = fmt.Sprintf("%d", m.End)
	}
	s := fmt.Sprintf("%s %.1f%% %d,%s", m.Name, m.Percent, m.Start, hi)
	if m.IsURL {
		s += " URL"
	}
	return s
}

// parsePercent parses a percentage (float ending in %).
func parsePercent(s string) (float64, error) {
	if !strings.HasSuffix(s, "%") {
		return 0, fmt.Errorf("missing %% suffix")
	}
	return strconv.ParseFloat(s[:len(s)-len("%")], 64)
}

// parseRange parses a start,end range (two decimals separated by a comma).
// As a special case, the second decimal can be $ meaning end-of-file.
func parseRange(s string, end int) (int, int, error) {
	i := strings.Index(s, ",")
	if i < 0 {
		return 0, 0, fmt.Errorf("malformed range")
	}
	lo, err := strconv.Atoi(s[:i])
	if err != nil {
		return 0, 0, err
	}
	var hi int
	if s[i+1:] == "$" {
		hi = end
	} else {
		hi, err = strconv.Atoi(s[i+1:])
		if err != nil {
			return 0, 0, err
		}
	}
	return lo, hi, nil
}

// matchPercent reports whether have matches want.
// We require that they match to within 0.1.
func matchPercent(have, want float64) bool {
	return math.Abs(have-want) < 0.1
}

// matchMatch reports whether have matches want.
func matchMatch(have, want Match) bool {
	return have.Name == want.Name &&
		matchPercent(have.Percent, want.Percent) &&
		have.Start == want.Start &&
		have.End == want.End &&
		have.IsURL == want.IsURL
}

var benchdata []byte

func BenchmarkTestdata(b *testing.B) {
	if benchdata == nil {
		files, err := filepath.Glob("testdata/*")
		if err != nil {
			b.Fatal(err)
		}
		if len(files) == 0 {
			b.Fatalf("no testdata files found")
		}
		for _, file := range files {
			data, err := ioutil.ReadFile(file)
			if err != nil {
				b.Fatal(err)
			}
			benchdata = append(benchdata, data...)
		}
		b.ResetTimer()
	}

	b.SetBytes(int64(len(benchdata)))
	for i := 0; i < b.N; i++ {
		Cover(benchdata, Options{})
	}
}
<commit_msg>licensecheck: add testdata file name to two more test failure messages<commit_after>// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package licensecheck

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"math"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
)

func TestTestdata(t *testing.T) {
	files, err := filepath.Glob("testdata/*")
	if err != nil {
		t.Fatal(err)
	}
	if len(files) == 0 {
		t.Fatalf("no testdata files found")
	}

	for _, file := range files {
		name := filepath.Base(file)
		if name == "README" {
			continue
		}
		t.Run(file, func(t *testing.T) {
			t.Parallel() // faster and tests for races in parallel usage
			data, err := ioutil.ReadFile(file)
			if err != nil {
				t.Fatal(err)
			}

			// See testdata/README for definition of test data file.
			// Header ends at blank line.
			i := bytes.Index(data, []byte("\n\n"))
			if i < 0 {
				t.Fatalf("%s: invalid test data file: no blank line terminating header", file)
			}
			hdr, data := strings.Split(string(data[:i]), "\n"), data[i+2:]

			lineno := 1
			// Skip leading comment lines.
			for len(hdr) > 0 && strings.HasPrefix(hdr[0], "#") {
				hdr = hdr[1:]
				lineno++
			}

			if len(hdr) > 0 && strings.HasPrefix(hdr[0], "set ") {
				t.Fatalf("%s:%d: set not implemented", file, lineno)
				hdr = hdr[1:]
				lineno++
			}
			if len(hdr) < 1 {
				t.Fatalf("%s: header too short", file)
			}

			linenoStart := lineno
			var want Coverage
			want.Percent, err = parsePercent(hdr[0])
			if err != nil {
				t.Fatalf("%s:%d: parsing want.Percent: %v", file, lineno, err)
			}
			hdr = hdr[1:]
			lineno++
			want.Match = make([]Match, len(hdr))
			for i, line := range hdr {
				f := strings.Fields(line)
				if len(f) != 3 && len(f) != 4 {
					t.Fatalf("%s:%d: bad match field count", file, lineno)
				}
				m := &want.Match[i]
				m.Name = f[0]
				m.Percent, err = parsePercent(f[1])
				if err != nil {
					t.Fatalf("%s:%d: parsing want.Match[%d].Percent: %v", file, lineno, i, err)
				}
				m.Start, m.End, err = parseRange(f[2], len(data))
				if err != nil {
					t.Fatalf("%s:%d: parsing want.Match[%d].Start,End: %v", file, lineno, i, err)
				}
				if len(f) == 4 {
					if f[3] != "URL" {
						t.Fatalf("%s:%d: field 3 should not be omitted or should be 'URL'", file, lineno)
					}
					m.IsURL = true
				}
				lineno++
			}
			linenoEnd := lineno

			cov, ok := Cover(data, Options{})
			if (len(cov.Match) > 0) != ok {
				t.Errorf("len(cov.Match)=%d but ok=%v, want %v", len(cov.Match), ok, !ok)
			}

			mismatch := false
			var buf bytes.Buffer
			if !matchPercent(cov.Percent, want.Percent) {
				fmt.Fprintf(&buf, "- %.1f%%\n+ %.1f%%\n", want.Percent, cov.Percent)
				mismatch = true
			} else {
				fmt.Fprintf(&buf, "  %.1f%%\n", cov.Percent)
			}

			covm, wantm := cov.Match, want.Match
			for len(covm) > 0 || len(wantm) > 0 {
				switch {
				case len(covm) > 0 && (len(wantm) == 0 || covm[0].End < wantm[0].Start):
					fmt.Fprintf(&buf, "+ %v\n", fmtMatch(covm[0], len(data)))
					covm = covm[1:]
					mismatch = true

				case len(covm) > 0 && len(wantm) > 0 && matchMatch(covm[0], wantm[0]):
					fmt.Fprintf(&buf, "  %v\n", fmtMatch(covm[0], len(data)))
					covm = covm[1:]
					wantm = wantm[1:]

				default:
					fmt.Fprintf(&buf, "- %v\n", fmtMatch(wantm[0], len(data)))
					wantm = wantm[1:]
					mismatch = true
				}
			}
			if mismatch {
				t.Errorf("%s:%d,%d: diff -want +have:\n%s", file, linenoStart, linenoEnd, buf.Bytes())
			}
		})
	}
}

// fmtMatch formats the match m for printing.
func fmtMatch(m Match, end int) string {
	// Special case for EOF end position.
	var hi string
	if m.End == end {
		hi = "$"
	} else {
		hi = fmt.Sprintf("%d", m.End)
	}
	s := fmt.Sprintf("%s %.1f%% %d,%s", m.Name, m.Percent, m.Start, hi)
	if m.IsURL {
		s += " URL"
	}
	return s
}

// parsePercent parses a percentage (float ending in %).
func parsePercent(s string) (float64, error) {
	if !strings.HasSuffix(s, "%") {
		return 0, fmt.Errorf("missing %% suffix")
	}
	return strconv.ParseFloat(s[:len(s)-len("%")], 64)
}

// parseRange parses a start,end range (two decimals separated by a comma).
// As a special case, the second decimal can be $ meaning end-of-file.
func parseRange(s string, end int) (int, int, error) {
	i := strings.Index(s, ",")
	if i < 0 {
		return 0, 0, fmt.Errorf("malformed range")
	}
	lo, err := strconv.Atoi(s[:i])
	if err != nil {
		return 0, 0, err
	}
	var hi int
	if s[i+1:] == "$" {
		hi = end
	} else {
		hi, err = strconv.Atoi(s[i+1:])
		if err != nil {
			return 0, 0, err
		}
	}
	return lo, hi, nil
}

// matchPercent reports whether have matches want.
// We require that they match to within 0.1.
func matchPercent(have, want float64) bool {
	return math.Abs(have-want) < 0.1
}

// matchMatch reports whether have matches want.
func matchMatch(have, want Match) bool {
	return have.Name == want.Name &&
		matchPercent(have.Percent, want.Percent) &&
		have.Start == want.Start &&
		have.End == want.End &&
		have.IsURL == want.IsURL
}

var benchdata []byte

func BenchmarkTestdata(b *testing.B) {
	if benchdata == nil {
		files, err := filepath.Glob("testdata/*")
		if err != nil {
			b.Fatal(err)
		}
		if len(files) == 0 {
			b.Fatalf("no testdata files found")
		}
		for _, file := range files {
			data, err := ioutil.ReadFile(file)
			if err != nil {
				b.Fatal(err)
			}
			benchdata = append(benchdata, data...)
		}
		b.ResetTimer()
	}

	b.SetBytes(int64(len(benchdata)))
	for i := 0; i < b.N; i++ {
		Cover(benchdata, Options{})
	}
}
<|endoftext|>


<commit_before>package mod_test

import (
	"io/ioutil"
	"net/http"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	prometheus_text "github.com/prometheus/client_golang/text"
	"github.com/robustirc/bridge/robustsession"
	"github.com/robustirc/robustirc/localnet"
	"github.com/robustirc/robustirc/types"
	"github.com/robustirc/robustirc/util"
)

func TestMessageOfDeath(t *testing.T) {
	tempdir, err := ioutil.TempDir("", "robustirc-message-of-death-")
	if err != nil {
		t.Fatalf("Could not create tempdir: %v", err)
	}

	l, err := localnet.NewLocalnet(-1, tempdir)
	if err != nil {
		t.Fatalf("Could not start local RobustIRC network: %v", err)
	}
	defer l.Kill(true)

	l.EnablePanicCommand = "1"

	// For each of the nodes, start a goroutine that verifies that the node crashes, then start it again
	var wg sync.WaitGroup

	for i := 0; i < 3; i++ {
		cmd, tempdir, addr := l.StartIRCServer(i == 0)
		wg.Add(1)
		go func(cmd *exec.Cmd, tempdir string, addr string) {
			defer wg.Done()

			terminated := make(chan error)
			skipped := make(chan bool)

			go func() {
				terminated <- cmd.Wait()
			}()

			go func() {
				// Poll messages of death counter.
				parser := &prometheus_text.Parser{}
				for {
					time.Sleep(50 * time.Millisecond)
					req, err := http.NewRequest("GET", addr+"metrics", nil)
					if err != nil {
						continue
					}
					resp, err := l.Httpclient.Do(req)
					if err != nil {
						continue
					}
					if resp.StatusCode != http.StatusOK {
						continue
					}
					metrics, err := parser.TextToMetricFamilies(resp.Body)
					if err != nil {
						continue
					}
					applied, ok := metrics["applied_messages"]
					if !ok {
						continue
					}
					for _, m := range applied.GetMetric() {
						for _, labelpair := range m.GetLabel() {
							if labelpair.GetName() == "type" &&
								labelpair.GetValue() == types.RobustType(types.RobustMessageOfDeath).String() {
								if m.GetCounter().GetValue() > 0 {
									skipped <- true
								}
							}
						}
					}
				}
			}()

			// Wait for the server to either crash or skip a message of death.
			select {
			case <-terminated:
				t.Logf("Node terminated (as expected)")
			case <-skipped:
				t.Logf("Node skipped message of death")
			}

			// Run restart.sh for that node.
			rcmd := exec.Command(filepath.Join(tempdir, "restart.sh"))
			if err := rcmd.Start(); err != nil {
				t.Errorf("Cannot restart node: %v", err)
				return
			}
			l.RecordResource("pid", strconv.Itoa(cmd.Process.Pid))

			// Ensure the node comes back up.
			started := time.Now()
			for time.Since(started) < 10*time.Second {
				if _, err := util.GetServerStatus(addr, l.NetworkPassword); err != nil {
					t.Logf("Node %s unhealthy: %v", addr, err)
					time.Sleep(1 * time.Second)
					continue
				}
				t.Logf("Node %s became healthy", addr)
				return
			}
			t.Errorf("Node did not become healthy within 10s")
		}(cmd, tempdir, addr)
	}

	// Connect and send the PANIC message.
	session, err := robustsession.Create(strings.Join(l.Servers(), ","), filepath.Join(tempdir, "cert.pem"))
	if err != nil {
		t.Fatalf("Could not create robustsession: %v", err)
	}
	foundjoin := make(chan bool)
	go func() {
		for msg := range session.Messages {
			if !strings.HasPrefix(msg, ":mod!1@") ||
				!strings.HasSuffix(msg, " JOIN :#mod") {
				continue
			}
			select {
			case foundjoin <- true:
			default:
				t.Errorf("Found JOIN too early (channel write blocks)")
			}
		}
	}()
	go func() {
		for err := range session.Errors {
			t.Errorf("RobustSession error: %v", err)
		}
	}()

	session.PostMessage("NICK mod")
	session.PostMessage("USER 1 2 3 4")
	session.PostMessage("PANIC")

	t.Logf("Message of death sent")

	wg.Wait()

	if !l.Healthy() {
		t.Fatalf("Expected recovery, but not all nodes are healthy")
	}

	// Verify sending a JOIN now results in an output message.
	session.PostMessage("JOIN #mod")
	select {
	case <-foundjoin:
		t.Logf("JOIN reply received, network progressing")
	case <-time.After(5 * time.Second):
		t.Errorf("Timeout waiting for JOIN message")
	}
}
<commit_msg>mod_test: allow for some time until the network becomes healthy<commit_after>package mod_test

import (
	"io/ioutil"
	"net/http"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	prometheus_text "github.com/prometheus/client_golang/text"
	"github.com/robustirc/bridge/robustsession"
	"github.com/robustirc/robustirc/localnet"
	"github.com/robustirc/robustirc/types"
	"github.com/robustirc/robustirc/util"
)

func TestMessageOfDeath(t *testing.T) {
	tempdir, err := ioutil.TempDir("", "robustirc-message-of-death-")
	if err != nil {
		t.Fatalf("Could not create tempdir: %v", err)
	}

	l, err := localnet.NewLocalnet(-1, tempdir)
	if err != nil {
		t.Fatalf("Could not start local RobustIRC network: %v", err)
	}
	defer l.Kill(true)

	l.EnablePanicCommand = "1"

	// For each of the nodes, start a goroutine that verifies that the node crashes, then start it again
	var wg sync.WaitGroup

	for i := 0; i < 3; i++ {
		cmd, tempdir, addr := l.StartIRCServer(i == 0)
		wg.Add(1)
		go func(cmd *exec.Cmd, tempdir string, addr string) {
			defer wg.Done()

			terminated := make(chan error)
			skipped := make(chan bool)

			go func() {
				terminated <- cmd.Wait()
			}()

			go func() {
				// Poll messages of death counter.
				parser := &prometheus_text.Parser{}
				for {
					time.Sleep(50 * time.Millisecond)
					req, err := http.NewRequest("GET", addr+"metrics", nil)
					if err != nil {
						continue
					}
					resp, err := l.Httpclient.Do(req)
					if err != nil {
						continue
					}
					if resp.StatusCode != http.StatusOK {
						continue
					}
					metrics, err := parser.TextToMetricFamilies(resp.Body)
					if err != nil {
						continue
					}
					applied, ok := metrics["applied_messages"]
					if !ok {
						continue
					}
					for _, m := range applied.GetMetric() {
						for _, labelpair := range m.GetLabel() {
							if labelpair.GetName() == "type" &&
								labelpair.GetValue() == types.RobustType(types.RobustMessageOfDeath).String() {
								if m.GetCounter().GetValue() > 0 {
									skipped <- true
								}
							}
						}
					}
				}
			}()

			// Wait for the server to either crash or skip a message of death.
			select {
			case <-terminated:
				t.Logf("Node terminated (as expected)")
			case <-skipped:
				t.Logf("Node skipped message of death")
			}

			// Run restart.sh for that node.
			rcmd := exec.Command(filepath.Join(tempdir, "restart.sh"))
			if err := rcmd.Start(); err != nil {
				t.Errorf("Cannot restart node: %v", err)
				return
			}
			l.RecordResource("pid", strconv.Itoa(cmd.Process.Pid))

			// Ensure the node comes back up.
			started := time.Now()
			for time.Since(started) < 10*time.Second {
				if _, err := util.GetServerStatus(addr, l.NetworkPassword); err != nil {
					t.Logf("Node %s unhealthy: %v", addr, err)
					time.Sleep(1 * time.Second)
					continue
				}
				t.Logf("Node %s became healthy", addr)
				return
			}
			t.Errorf("Node did not become healthy within 10s")
		}(cmd, tempdir, addr)
	}

	// Connect and send the PANIC message.
	session, err := robustsession.Create(strings.Join(l.Servers(), ","), filepath.Join(tempdir, "cert.pem"))
	if err != nil {
		t.Fatalf("Could not create robustsession: %v", err)
	}
	foundjoin := make(chan bool)
	go func() {
		for msg := range session.Messages {
			if !strings.HasPrefix(msg, ":mod!1@") ||
				!strings.HasSuffix(msg, " JOIN :#mod") {
				continue
			}
			select {
			case foundjoin <- true:
			default:
				t.Errorf("Found JOIN too early (channel write blocks)")
			}
		}
	}()
	go func() {
		for err := range session.Errors {
			t.Errorf("RobustSession error: %v", err)
		}
	}()

	session.PostMessage("NICK mod")
	session.PostMessage("USER 1 2 3 4")
	session.PostMessage("PANIC")

	t.Logf("Message of death sent")

	wg.Wait()

	healthy := false
	for try := 0; try < 5; try++ {
		if l.Healthy() {
			healthy = true
			break
		}
		time.Sleep(1 * time.Second)
	}

	if !healthy {
		t.Fatalf("Expected recovery, but not all nodes are healthy")
	}

	// Verify sending a JOIN now results in an output message.
	session.PostMessage("JOIN #mod")
	select {
	case <-foundjoin:
		t.Logf("JOIN reply received, network progressing")
	case <-time.After(5 * time.Second):
		t.Errorf("Timeout waiting for JOIN message")
	}
}
<|endoftext|>


<commit_before>package DAO

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"errors"
	"io"
	"net/http"
	"net/url"
	"sync"
)

// encrypt method is aes256
const (
	TOKEN_LENGTH = 32
)

var (
	KEY            = []byte("XY0nG86PSRJqMGz957Yza1D34393MPII") // 32 bytes
	provides       = make(map[string]Provider)
	globalSessions *Manager
)

type Manager struct {
	cookieName  string
	lock        sync.Mutex
	provider    Provider
	maxlifetime int64
}

func NewManager(providerName, cookieName string, maklifetime int64) (*Manager, error) {
	return nil, nil
}

type Provider interface {
	SessionInit(sid string) (Session, error)
	SessionRead(sid string) (Session, error)
	SessionDestroy(sid string) error
	SessionGC(maxLifeTime int64)
}

type Session interface {
	Set(key, value interface{}) error //set session value
	Get(key interface{}) interface{}  //get session value
	Delete(key interface{}) error     //delete session value
	SessionID() string                //back current sessionID
}

func Register(name string, provider Provider) {
	if provider == nil {
		panic("session: Register provide is nil")
	}
	if _, dup := provides[name]; dup {
		panic("session: Register called twice for provider" + name)
	}
	provides[name] = provider
}

func (manager *Manager) sessionId() (string, error) {
	// change the length of the generated random string here
	size := TOKEN_LENGTH

	rb := make([]byte, size)
	_, err := rand.Read(rb)
	if err != nil {
		return "error", errors.New("cannot generate token for user")
	}
	rs := base64.URLEncoding.EncodeToString(rb)
	return rs, nil
}

func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Session) {
	manager.lock.Lock()
	defer manager.lock.Unlock()
	cookie, err := r.Cookie(manager.cookieName)
	if err != nil || cookie.Value != "" {
		sid := manager.sessionId()
		session, _ = manager.provider.SessionInit(sid)
		cookie := http.Cookie{Name: manager.cookieName, value: url.QueryEscape(sid), Path: "/", HttpOnly: true, MaxAge: int(manager.maxlifetime)}
		http.SetCookie(w, &cookie)
	} else {
		sid, _ := url.QueryEscape(cookie.Value)
		session, _ = manager.provider.SessionRead(sid)
	}

	return
}

func login(w http.ResponseWriter, r *http.Request) {
	session := globalSessions.SessionStart(w, r)
	r.ParseForm()
	session.Set("username", r.Form["username"])
	http.Redirect(w, r, "/", 302)
}

func PerformLogin(uname string, pwd string) (string, bool) {
	// this method is not finished
	userDao := NewUserDAO()
	manager, _ := NewManager("providerName", "cookieName", 0)
	user := userDao.GetUserByName(uname)
	hashpwd, err := decrypt(user.Pwd, KEY)
	if err != nil {
		return "", false
	}
	if pwd == hashpwd {
		token, err := manager.sessionId()
		if err != nil {
			return token, false
		} else {
			return token, true
		}
	} else {
		return "wrong password", false
	}
}

func PerformLogout(token string) {
	// todo this is a sub
}

func ValidateToken(token string) bool {
	return true
}

func encrypt(str string, key []byte) (string, error) {
	text := []byte(str)
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	b := base64.StdEncoding.EncodeToString(text)
	ciphertext := make([]byte, aes.BlockSize+len(b))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}
	cfb := cipher.NewCFBEncrypter(block, iv)
	cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
	return string(ciphertext[:]), nil
}

func decrypt(str string, key []byte) (string, error) {
	text := []byte(str)
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	if len(text) < aes.BlockSize {
		return "", errors.New("ciphertext too short")
	}
	iv := text[:aes.BlockSize]
	text = text[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(text, text)
	data, err := base64.StdEncoding.DecodeString(string(text))
	if err != nil {
		return "", err
	}
	return string(data[:]), nil
}

func init() {
	globalSessions, _ = NewManager("memory", "gosessionid", 3600)
}
<commit_msg>init commit of session management<commit_after>package DAO

import (
	"container/list"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"errors"
	"io"
	"net/http"
	"net/url"
	"sync"
	"time"
)

// encrypt method is aes256
const (
	TOKEN_LENGTH = 32
)

var (
	KEY            = []byte("XY0nG86PSRJqMGz957Yza1D34393MPII") // 32 bytes
	provides       = make(map[string]Provider)
	globalSessions *Manager
	pder           = &ProviderImpl{list: list.New()}
)

type Manager struct {
	cookieName  string
	lock        sync.Mutex
	provider    Provider
	maxlifetime int64
}

func NewManager(providerName, cookieName string, maklifetime int64) (*Manager, error) {
	provider, ok := provides[provideName]
	if !ok {
		return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
	}
	return &Manager{provider: provider, cookieName: cookieName, maxlifetime: maxlifetime}, nil
}

type Provider interface {
	SessionInit(sid string) (Session, error)
	SessionRead(sid string) (Session, error)
	SessionUpdate(sid string) error
	SessionDestroy(sid string) error
	SessionGC(maxLifeTime int64)
}

type ProviderImpl struct {
	lock     sync.Mutex               // locker
	sessions map[string]*list.Element // save to memory
	list     *list.List               // gc()
}

type Session interface {
	Set(key, value interface{}) error //set session value
	Get(key interface{}) interface{}  //get session value
	Delete(key interface{}) error     //delete session value
	SessionID() string                //back current sessionID
}

type SessionStore struct {
	sid          string                      // session id rule
	timeAccessed time.Time                   // last vist time
	value        map[interface{}]interface{} // sesiion value
}

func (st *SessionStore) Set(key, value interface{}) error {
	st.value[kye] = value
	pder.SessionUpdate(st.sid)
	return nil
}

func (st *SessionStore) Get(key interface{}) interface{} {
	pder.SessionUpdate(st.sid)
	if v, ok := st.value[key]; ok {
		return v
	} else {
		return nil
	}
	return nil
}

func (st *SessionStore) Delete(key interface{}) error {
	delete(st.value, key)
	pder.SessionUpdate(st.sid)
	return nil
}

func (st *SessionStore) SessionID() string {
	return st.sid
}

/////////////////////////////////////////////////////////
////////////////////// Session management ///////////////
func (pder *ProviderImpl) SessionInit(sid string) (session.Session, error) {
	pder.lock.Lock()
	defer pder.lock.Unlock()
	v := make(map[interface{}]interface{}, 0)
	newsess := &SessionStore{sid: sid, timeAccessed: time.Now(), value: v}
	element := pder.list.PushBack(newsess)
	pder.sessions[sid] = element
	return newsess, nil
}

func (pder *ProviderImpl) SessionRead(sid string) (session.Session, error) {
	if element, ok := pder.sessions[sid]; ok {
		return element.Value.(*SessionStore), nil
	} else {
		sess, err := pder.SessionInit(sid)
		return sess, err
	}
	return nil, nil
}

func (pder *ProviderImpl) SessionDestroy(sid string) error {
	if element, ok := pder.sessions[sid]; ok {
		delete(pder.sessions, sid)
		pder.list.Remove(element)
		return nil
	}
	return nil
}

func (pder *ProviderImpl) SessionGC(maxlifetime int64) {
	pder.lock.Lock()
	defer pder.lock.Unlock()

	for {
		element := pder.list.Back()
		if element == nil {
			break
		}
		if (element.Value.(*SessionStore).timeAccessed.Unix() + maxlifetime) < time.Now().Unix() {
			pder.list.Remove(element)
			delete(pder.sessions, element.Value.(*SessionStore).sid)
		} else {
			break
		}
	}
}

func (pder *ProviderImpl) SessionUpdate(sid string) error {
	pder.lock.Lock()
	defer pder.lock.Unlock()
	if element, ok := pder.sessions[sid]; ok {
		element.Value.(*SessionStore).timeAccessed = time.Now()
		pder.list.MoveToFront(element)
		return nil
	}
	return nil
}

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

func Register(name string, provider Provider) {
	if provider == nil {
		panic("session: Register provide is nil")
	}
	if _, dup := provides[name]; dup {
		panic("session: Register called twice for provider" + name)
	}
	provides[name] = provider
}

func (manager *Manager) sessionId() (string, error) {
	// change the length of the generated random string here
	size := TOKEN_LENGTH

	rb := make([]byte, size)
	_, err := rand.Read(rb)
	if err != nil {
		return "error", errors.New("cannot generate token for user")
	}
	rs := base64.URLEncoding.EncodeToString(rb)
	return rs, nil
}

func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Session) {
	manager.lock.Lock()
	defer manager.lock.Unlock()
	cookie, err := r.Cookie(manager.cookieName)
	if err != nil || cookie.Value != "" {
		sid := manager.sessionId()
		session, _ = manager.provider.SessionInit(sid)
		cookie := http.Cookie{Name: manager.cookieName, value: url.QueryEscape(sid), Path: "/", HttpOnly: true, MaxAge: int(manager.maxlifetime)}
		http.SetCookie(w, &cookie)
	} else {
		sid, _ := url.QueryEscape(cookie.Value)
		session, _ = manager.provider.SessionRead(sid)
	}

	return
}

func login(w http.ResponseWriter, r *http.Request) {
	session := globalSessions.SessionStart(w, r)
	r.ParseForm()
	session.Set("username", r.Form["username"])
	http.Redirect(w, r, "/", 302)
}

func PerformLogin(uname string, pwd string) (string, bool) {
	// this method is not finished
	userDao := NewUserDAO()
	manager, _ := NewManager("providerName", "cookieName", 0)
	user := userDao.GetUserByName(uname)
	hashpwd, err := decrypt(user.Pwd, KEY)
	if err != nil {
		return "", false
	}
	if pwd == hashpwd {
		token, err := manager.sessionId()
		if err != nil {
			return token, false
		} else {
			return token, true
		}
	} else {
		return "wrong password", false
	}
}

func PerformLogout(token string) {
	// todo this is a sub
}

func ValidateToken(token string) bool {
	return true
}

func encrypt(str string, key []byte) (string, error) {
	text := []byte(str)
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	b := base64.StdEncoding.EncodeToString(text)
	ciphertext := make([]byte, aes.BlockSize+len(b))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}
	cfb := cipher.NewCFBEncrypter(block, iv)
	cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
	return string(ciphertext[:]), nil
}

func decrypt(str string, key []byte) (string, error) {
	text := []byte(str)
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	if len(text) < aes.BlockSize {
		return "", errors.New("ciphertext too short")
	}
	iv := text[:aes.BlockSize]
	text = text[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(text, text)
	data, err := base64.StdEncoding.DecodeString(string(text))
	if err != nil {
		return "", err
	}
	return string(data[:]), nil
}

func init() {
	pder.sessions = make(map[string]*list.Element, 0)
	Register("memory", pder)
	globalSessions, _ = NewManager("memory", "gosessionid", 3600)
}
<|endoftext|>


<commit_before>// Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package models

import (
	"fmt"

	"github.com/Unknwon/com"

	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/markdown"
	"code.gitea.io/gitea/modules/setting"
)

func (issue *Issue) mailSubject() string {
	return fmt.Sprintf("[%s] %s (#%d)", issue.Repo.Name, issue.Title, issue.Index)
}

// mailIssueCommentToParticipants can be used only for comment.
// This function sends two list of emails:
// 1. Repository watchers and users who are participated in comments.
// 2. Users who are not in 1. but get mentioned in current issue/comment.
func mailIssueCommentToParticipants(issue *Issue, doer *User, comment *Comment, mentions []string) error {
	if !setting.Service.EnableNotifyMail {
		return nil
	}

	watchers, err := GetWatchers(issue.RepoID)
	if err != nil {
		return fmt.Errorf("GetWatchers [repo_id: %d]: %v", issue.RepoID, err)
	}
	participants, err := GetParticipantsByIssueID(issue.ID)
	if err != nil {
		return fmt.Errorf("GetParticipantsByIssueID [issue_id: %d]: %v", issue.ID, err)
	}

	// In case the issue poster is not watching the repository,
	// even if we have duplicated in watchers, can be safely filtered out.
	if issue.PosterID != doer.ID {
		participants = append(participants, issue.Poster)
	}

	tos := make([]string, 0, len(watchers)) // List of email addresses.
	names := make([]string, 0, len(watchers))
	for i := range watchers {
		if watchers[i].UserID == doer.ID {
			continue
		}

		to, err := GetUserByID(watchers[i].UserID)
		if err != nil {
			return fmt.Errorf("GetUserByID [%d]: %v", watchers[i].UserID, err)
		}
		if to.IsOrganization() {
			continue
		}

		tos = append(tos, to.Email)
		names = append(names, to.Name)
	}
	for i := range participants {
		if participants[i].ID == doer.ID {
			continue
		} else if com.IsSliceContainsStr(names, participants[i].Name) {
			continue
		}

		tos = append(tos, participants[i].Email)
		names = append(names, participants[i].Name)
	}

	SendIssueCommentMail(issue, doer, comment, tos)

	// Mail mentioned people and exclude watchers.
	names = append(names, doer.Name)
	tos = make([]string, 0, len(mentions)) // list of user names.
	for i := range mentions {
		if com.IsSliceContainsStr(names, mentions[i]) {
			continue
		}

		tos = append(tos, mentions[i])
	}
	SendIssueMentionMail(issue, doer, comment, GetUserEmailsByNames(tos))

	return nil
}

// mailIssueActionToParticipants can be used for creation or pull requests.
// This function sends two list of emails:
// 1. Repository watchers and users who are participated in comments.
// 2. Users who are not in 1. but get mentioned in current issue/comment.
func mailIssueActionToParticipants(issue *Issue, doer *User, mentions []string) error {
	return mailIssueCommentToParticipants(issue, doer, nil, mentions)
}

// MailParticipants sends new issue thread created emails to repository watchers
// and mentioned people.
func (issue *Issue) MailParticipants() (err error) {
	mentions := markdown.FindAllMentions(issue.Content)
	if err = UpdateIssueMentions(x, issue.ID, mentions); err != nil {
		return fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
	}

	if err = mailIssueActionToParticipants(issue, issue.Poster, mentions); err != nil {
		log.Error(4, "mailIssueCommentToParticipants: %v", err)
	}

	return nil
}
<commit_msg>Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants.<commit_after>// Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package models

import (
	"fmt"

	"github.com/Unknwon/com"

	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/markdown"
	"code.gitea.io/gitea/modules/setting"
)

func (issue *Issue) mailSubject() string {
	return fmt.Sprintf("[%s] %s (#%d)", issue.Repo.Name, issue.Title, issue.Index)
}

// mailIssueCommentToParticipants can be used only for comment.
// This function sends two list of emails:
// 1. Repository watchers and users who are participated in comments.
// 2. Users who are not in 1. but get mentioned in current issue/comment.
func mailIssueCommentToParticipants(issue *Issue, doer *User, comment *Comment, mentions []string) error {
	if !setting.Service.EnableNotifyMail {
		return nil
	}

	watchers, err := GetWatchers(issue.RepoID)
	if err != nil {
		return fmt.Errorf("GetWatchers [repo_id: %d]: %v", issue.RepoID, err)
	}
	participants, err := GetParticipantsByIssueID(issue.ID)
	if err != nil {
		return fmt.Errorf("GetParticipantsByIssueID [issue_id: %d]: %v", issue.ID, err)
	}

	// In case the issue poster is not watching the repository,
	// even if we have duplicated in watchers, can be safely filtered out.
	if issue.PosterID != doer.ID {
		participants = append(participants, issue.Poster)
	}

	tos := make([]string, 0, len(watchers)) // List of email addresses.
	names := make([]string, 0, len(watchers))
	for i := range watchers {
		if watchers[i].UserID == doer.ID {
			continue
		}

		to, err := GetUserByID(watchers[i].UserID)
		if err != nil {
			return fmt.Errorf("GetUserByID [%d]: %v", watchers[i].UserID, err)
		}
		if to.IsOrganization() {
			continue
		}

		tos = append(tos, to.Email)
		names = append(names, to.Name)
	}
	for i := range participants {
		if participants[i].ID == doer.ID {
			continue
		} else if com.IsSliceContainsStr(names, participants[i].Name) {
			continue
		}

		tos = append(tos, participants[i].Email)
		names = append(names, participants[i].Name)
	}

	SendIssueCommentMail(issue, doer, comment, tos)

	// Mail mentioned people and exclude watchers.
	names = append(names, doer.Name)
	tos = make([]string, 0, len(mentions)) // list of user names.
	for i := range mentions {
		if com.IsSliceContainsStr(names, mentions[i]) {
			continue
		}

		tos = append(tos, mentions[i])
	}
	SendIssueMentionMail(issue, doer, comment, GetUserEmailsByNames(tos))

	return nil
}

// MailParticipants sends new issue thread created emails to repository watchers
// and mentioned people.
func (issue *Issue) MailParticipants() (err error) {
	mentions := markdown.FindAllMentions(issue.Content)
	if err = UpdateIssueMentions(x, issue.ID, mentions); err != nil {
		return fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
	}

	if err = mailIssueCommentToParticipants(issue, issue.Poster, nil, mentions); err != nil {
		log.Error(4, "mailIssueCommentToParticipants: %v", err)
	}

	return nil
}
<|endoftext|>


<commit_before>package models

import (
	"testing"
	"time"

	"bitbucket.org/mundipagg/boletoapi/test"
)

func TestShouldReturnValidCpfOnDocumentType(t *testing.T) {
	document := Document{Number: "12345678901", Type: "CPF"}
	if document.Type.IsCpf() == false {
		t.Fail()
	}
}

func TestShouldReturnInvalidCpfOnDocumentType(t *testing.T) {
	document := Document{Number: "1234567890132", Type: "CNPJ"}
	if document.Type.IsCpf() {
		t.Fail()
	}
}

func TestShouldReturnValidCnpjOnDocumentType(t *testing.T) {
	document := Document{Number: "1234567890132", Type: "CnpJ"}
	if document.Type.IsCnpj() == false {
		t.Fail()
	}
}

func TestShouldReturnInvalidCnpjOnDocumentType(t *testing.T) {
	document := Document{Number: "12345678901", Type: "CPF"}
	if document.Type.IsCnpj() {
		t.Fail()
	}
}

func TestShouldReturnValidCpfOnDocumentNumber(t *testing.T) {
	document := Document{Number: "12345678901", Type: "CPF"}
	if document.Number.IsCpf() == false {
		t.Fail()
	}
}

func TestShouldReturnInvalidCpfOnDocumentNumber(t *testing.T) {
	document := Document{Number: "12345678901asd", Type: "CPF"}
	if document.Number.IsCpf() {
		t.Fail()
	}
}

func TestShouldReturnValidCnpjOnDocumentNumber(t *testing.T) {
	document := Document{Number: "12345678901564", Type: "CNPJ"}
	if document.Number.IsCnpj() == false {
		t.Fail()
	}
}

func TestShouldReturnInvalidCnpjOnDocumentNumber(t *testing.T) {
	document := Document{Number: "12345678901564asdf", Type: "CNPJ"}
	if document.Number.IsCnpj() {
		t.Fail()
	}
}

func TestShouldReturnNewTitle(t *testing.T) {
	expDate := time.Now().AddDate(0, 0, 6).Format("2006-01-02")
	_, err := NewTitle(expDate, 100, 231654)
	if err != nil {
		t.Fail()
	}
}

func TestShouldCreateNewTitleWithEqualExpireDateAndCreateDate(t *testing.T) {
	expDate := time.Now().Format("2006-01-02")
	_, err := NewTitle(expDate, 100, 231654)
	if err != nil {
		t.Fail()
	}
}

func TestShouldFailWithCreateDateBiggerThanExpireDate(t *testing.T) {
	expDate := time.Now().AddDate(0, 0, -6).Format("2006-01-02")
	_, err := NewTitle(expDate, 100, 231654)
	if err == nil {
		t.Fail()
	}
}

func TestShouldFailWithAmountInCentsMinorThanOne(t *testing.T) {
	expDate := time.Now().AddDate(0, 0, 6).Format("2006-01-02")
	_, err := NewTitle(expDate, 0, 231654)
	if err == nil {
		t.Fail()
	}
}

func TestShouldReturnBankNumberIsValid(t *testing.T) {
	var b BankNumber = 237

	if b.IsBankNumberValid() == false {
		t.Fail()
	}
}

func TestShouldAppendCollectionOfErrrors(t *testing.T) {
	e := NewErrorCollection(ErrorResponse{Code: "200", Message: "Hue2"})
	e.Append("100", "Hue")
	test.ExpectTrue(len(e) == 2, t)
}

func TestShouldCreateNewSingleErrorCollection(t *testing.T) {
	e := NewSingleErrorCollection("200", "Hue2")
	test.ExpectTrue(len(e) == 1, t)
}

func TestIsAgencyValid(t *testing.T) {
	a := Agreement{
		Agency: "234-2a",
	}
	err := a.IsAgencyValid()
	test.ExpectNoError(err, t)
	test.ExpectTrue(a.Agency == "2342", t)
}

func TestIsAgencyInValid(t *testing.T) {
	a := Agreement{
		Agency: "234-2222a",
	}
	err := a.IsAgencyValid()
	test.ExpectError(err, t)
}

func TestIsAgencyValidWithLessThan4Digits(t *testing.T) {
	a := Agreement{
		Agency: "321",
	}
	err := a.IsAgencyValid()
	test.ExpectNoError(err, t)
	test.ExpectTrue(a.Agency == "0321", t)
}

func TestCalculateAgencyDigit(t *testing.T) {
	a := new(Agreement)
	a.AccountDigit = "1sssss"
	c := func(s string) string {
		return "1"
	}
	a.CalculateAgencyDigit(c)
	test.ExpectTrue(a.AgencyDigit == "1", t)
}

func WTestCalculateAgencyDigitWithInvalidDigit(t *testing.T) {
	a := Agreement{
		AgencyDigit: "",
	}
	c := func(s string) string {
		return "1"
	}
	a.CalculateAgencyDigit(c)
	test.ExpectTrue(a.AgencyDigit == "1", t)
}

func TestIsAccountDigitInValid(t *testing.T) {
	a := Agreement{
		AccountDigit: "",
	}
	_, err := a.IsAccountDigitValid()
	test.ExpectError(err, t)
}

func TestIsAccountDigitValid(t *testing.T) {
	a := Agreement{
		AccountDigit: "1sss",
	}
	s, err := a.IsAccountDigitValid()
	test.ExpectNoError(err, t)
	test.ExpectTrue(s == "1", t)
}

func TestIsAccountValid(t *testing.T) {
	a := Agreement{
		Account: "1234fff",
	}
	err := a.IsAccountValid(8)
	test.ExpectNoError(err, t)
	test.ExpectTrue(a.Account == "00001234", t)
}

func TestIsAccountInValid(t *testing.T) {
	a := Agreement{
		Account: "123456789",
	}
	err := a.IsAccountValid(8)
	test.ExpectError(err, t)
}
<commit_msg>:fire: remove testes de funções deletadas<commit_after>package models

import (
	"testing"
	"time"

	"bitbucket.org/mundipagg/boletoapi/test"
)

func TestShouldReturnValidCpfOnDocumentType(t *testing.T) {
	document := Document{Number: "12345678901", Type: "CPF"}
	if document.Type.IsCpf() == false {
		t.Fail()
	}
}

func TestShouldReturnInvalidCpfOnDocumentType(t *testing.T) {
	document := Document{Number: "1234567890132", Type: "CNPJ"}
	if document.Type.IsCpf() {
		t.Fail()
	}
}

func TestShouldReturnValidCnpjOnDocumentType(t *testing.T) {
	document := Document{Number: "1234567890132", Type: "CnpJ"}
	if document.Type.IsCnpj() == false {
		t.Fail()
	}
}

func TestShouldReturnInvalidCnpjOnDocumentType(t *testing.T) {
	document := Document{Number: "12345678901", Type: "CPF"}
	if document.Type.IsCnpj() {
		t.Fail()
	}
}

func TestShouldReturnValidCnpjOnDocumentNumber(t *testing.T) {
	document := Document{Number: "12345678901564", Type: "CNPJ"}
	if document.Number.IsCnpj() == false {
		t.Fail()
	}
}

func TestShouldReturnInvalidCnpjOnDocumentNumber(t *testing.T) {
	document := Document{Number: "12345678901564asdf", Type: "CNPJ"}
	if document.Number.IsCnpj() {
		t.Fail()
	}
}

func TestShouldReturnNewTitle(t *testing.T) {
	expDate := time.Now().AddDate(0, 0, 6).Format("2006-01-02")
	_, err := NewTitle(expDate, 100, 231654)
	if err != nil {
		t.Fail()
	}
}

func TestShouldCreateNewTitleWithEqualExpireDateAndCreateDate(t *testing.T) {
	expDate := time.Now().Format("2006-01-02")
	_, err := NewTitle(expDate, 100, 231654)
	if err != nil {
		t.Fail()
	}
}

func TestShouldFailWithCreateDateBiggerThanExpireDate(t *testing.T) {
	expDate := time.Now().AddDate(0, 0, -6).Format("2006-01-02")
	_, err := NewTitle(expDate, 100, 231654)
	if err == nil {
		t.Fail()
	}
}

func TestShouldFailWithAmountInCentsMinorThanOne(t *testing.T) {
	expDate := time.Now().AddDate(0, 0, 6).Format("2006-01-02")
	_, err := NewTitle(expDate, 0, 231654)
	if err == nil {
		t.Fail()
	}
}

func TestShouldReturnBankNumberIsValid(t *testing.T) {
	var b BankNumber = 237

	if b.IsBankNumberValid() == false {
		t.Fail()
	}
}

func TestShouldAppendCollectionOfErrrors(t *testing.T) {
	e := NewErrorCollection(ErrorResponse{Code: "200", Message: "Hue2"})
	e.Append("100", "Hue")
	test.ExpectTrue(len(e) == 2, t)
}

func TestShouldCreateNewSingleErrorCollection(t *testing.T) {
	e := NewSingleErrorCollection("200", "Hue2")
	test.ExpectTrue(len(e) == 1, t)
}

func TestIsAgencyValid(t *testing.T) {
	a := Agreement{
		Agency: "234-2a",
	}
	err := a.IsAgencyValid()
	test.ExpectNoError(err, t)
	test.ExpectTrue(a.Agency == "2342", t)
}

func TestIsAgencyInValid(t *testing.T) {
	a := Agreement{
		Agency: "234-2222a",
	}
	err := a.IsAgencyValid()
	test.ExpectError(err, t)
}

func TestIsAgencyValidWithLessThan4Digits(t *testing.T) {
	a := Agreement{
		Agency: "321",
	}
	err := a.IsAgencyValid()
	test.ExpectNoError(err, t)
	test.ExpectTrue(a.Agency == "0321", t)
}

func TestCalculateAgencyDigit(t *testing.T) {
	a := new(Agreement)
	a.AccountDigit = "1sssss"
	c := func(s string) string {
		return "1"
	}
	a.CalculateAgencyDigit(c)
	test.ExpectTrue(a.AgencyDigit == "1", t)
}

func WTestCalculateAgencyDigitWithInvalidDigit(t *testing.T) {
	a := Agreement{
		AgencyDigit: "",
	}
	c := func(s string) string {
		return "1"
	}
	a.CalculateAgencyDigit(c)
	test.ExpectTrue(a.AgencyDigit == "1", t)
}

func TestIsAccountDigitInValid(t *testing.T) {
	a := Agreement{
		AccountDigit: "",
	}
	_, err := a.IsAccountDigitValid()
	test.ExpectError(err, t)
}

func TestIsAccountDigitValid(t *testing.T) {
	a := Agreement{
		AccountDigit: "1sss",
	}
	s, err := a.IsAccountDigitValid()
	test.ExpectNoError(err, t)
	test.ExpectTrue(s == "1", t)
}

func TestIsAccountValid(t *testing.T) {
	a := Agreement{
		Account: "1234fff",
	}
	err := a.IsAccountValid(8)
	test.ExpectNoError(err, t)
	test.ExpectTrue(a.Account == "00001234", t)
}

func TestIsAccountInValid(t *testing.T) {
	a := Agreement{
		Account: "123456789",
	}
	err := a.IsAccountValid(8)
	test.ExpectError(err, t)
}
<|endoftext|>


<commit_before>/*
Copyright 2017 The Kubernetes Authors.

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

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

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

package blunderbuss

import (
	"context"
	"fmt"
	"regexp"

	githubql "github.com/shurcooL/githubv4"
	"github.com/sirupsen/logrus"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/test-infra/prow/pkg/layeredsets"

	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/github"
	"k8s.io/test-infra/prow/pluginhelp"
	"k8s.io/test-infra/prow/plugins"
	"k8s.io/test-infra/prow/plugins/assign"
	"k8s.io/test-infra/prow/repoowners"
)

const (
	// PluginName defines this plugin's registered name.
	PluginName = "blunderbuss"
)

var (
	match = regexp.MustCompile(`(?mi)^/auto-cc\s*$`)
)

func init() {
	plugins.RegisterPullRequestHandler(PluginName, handlePullRequestEvent, helpProvider)
	plugins.RegisterGenericCommentHandler(PluginName, handleGenericCommentEvent, helpProvider)
}

func configString(reviewCount int) string {
	var pluralSuffix string
	if reviewCount > 1 {
		pluralSuffix = "s"
	}
	return fmt.Sprintf("Blunderbuss is currently configured to request reviews from %d reviewer%s.", reviewCount, pluralSuffix)
}

func helpProvider(config *plugins.Configuration, _ []config.OrgRepo) (*pluginhelp.PluginHelp, error) {
	var reviewCount int
	if config.Blunderbuss.ReviewerCount != nil {
		reviewCount = *config.Blunderbuss.ReviewerCount
	}
	two := 2
	yamlSnippet, err := plugins.CommentMap.GenYaml(&plugins.Configuration{
		Blunderbuss: plugins.Blunderbuss{
			ReviewerCount:         &two,
			MaxReviewerCount:      3,
			ExcludeApprovers:      true,
			UseStatusAvailability: true,
		},
	})
	if err != nil {
		logrus.WithError(err).Warnf("cannot generate comments for %s plugin", PluginName)
	}
	pluginHelp := &pluginhelp.PluginHelp{
		Description: "The blunderbuss plugin automatically requests reviews from reviewers when a new PR is created. The reviewers are selected based on the reviewers specified in the OWNERS files that apply to the files modified by the PR.",
		Config: map[string]string{
			"": configString(reviewCount),
		},
		Snippet: yamlSnippet,
	}
	pluginHelp.AddCommand(pluginhelp.Command{
		Usage:       "/auto-cc",
		Featured:    false,
		Description: "Manually request reviews from reviewers for a PR. Useful if OWNERS file were updated since the PR was opened.",
		Examples:    []string{"/auto-cc"},
		WhoCanUse:   "Anyone",
	})
	return pluginHelp, nil
}

type reviewersClient interface {
	FindReviewersOwnersForFile(path string) string
	Reviewers(path string) layeredsets.String
	RequiredReviewers(path string) sets.String
	LeafReviewers(path string) sets.String
}

type ownersClient interface {
	reviewersClient
	FindApproverOwnersForFile(path string) string
	Approvers(path string) layeredsets.String
	LeafApprovers(path string) sets.String
}

type fallbackReviewersClient struct {
	ownersClient
}

func (foc fallbackReviewersClient) FindReviewersOwnersForFile(path string) string {
	return foc.ownersClient.FindApproverOwnersForFile(path)
}

func (foc fallbackReviewersClient) Reviewers(path string) layeredsets.String {
	return foc.ownersClient.Approvers(path)
}

func (foc fallbackReviewersClient) LeafReviewers(path string) sets.String {
	return foc.ownersClient.LeafApprovers(path)
}

type githubClient interface {
	RequestReview(org, repo string, number int, logins []string) error
	GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error)
	GetPullRequest(org, repo string, number int) (*github.PullRequest, error)
	Query(context.Context, interface{}, map[string]interface{}) error
}

type repoownersClient interface {
	LoadRepoOwners(org, repo, base string) (repoowners.RepoOwner, error)
}

func handlePullRequestEvent(pc plugins.Agent, pre github.PullRequestEvent) error {
	return handlePullRequest(
		pc.GitHubClient,
		pc.OwnersClient,
		pc.Logger,
		pc.PluginConfig.Blunderbuss,
		pre.Action,
		&pre.PullRequest,
		&pre.Repo,
	)
}

func handlePullRequest(ghc githubClient, roc repoownersClient, log *logrus.Entry, config plugins.Blunderbuss, action github.PullRequestEventAction, pr *github.PullRequest, repo *github.Repo) error {
	if action != github.PullRequestActionOpened || assign.CCRegexp.MatchString(pr.Body) {
		return nil
	}

	return handle(
		ghc,
		roc,
		log,
		config.ReviewerCount,
		config.MaxReviewerCount,
		config.ExcludeApprovers,
		config.UseStatusAvailability,
		repo,
		pr,
	)
}

func handleGenericCommentEvent(pc plugins.Agent, ce github.GenericCommentEvent) error {
	return handleGenericComment(
		pc.GitHubClient,
		pc.OwnersClient,
		pc.Logger,
		pc.PluginConfig.Blunderbuss,
		ce.Action,
		ce.IsPR,
		ce.Number,
		ce.IssueState,
		&ce.Repo,
		ce.Body,
	)
}

func handleGenericComment(ghc githubClient, roc repoownersClient, log *logrus.Entry, config plugins.Blunderbuss, action github.GenericCommentEventAction, isPR bool, prNumber int, issueState string, repo *github.Repo, body string) error {
	if action != github.GenericCommentActionCreated || !isPR || issueState == "closed" {
		return nil
	}

	if !match.MatchString(body) {
		return nil
	}

	pr, err := ghc.GetPullRequest(repo.Owner.Login, repo.Name, prNumber)
	if err != nil {
		return fmt.Errorf("error loading PullRequest: %w", err)
	}

	return handle(
		ghc,
		roc,
		log,
		config.ReviewerCount,
		config.MaxReviewerCount,
		config.ExcludeApprovers,
		config.UseStatusAvailability,
		repo,
		pr,
	)
}

func handle(ghc githubClient, roc repoownersClient, log *logrus.Entry, reviewerCount *int, maxReviewers int, excludeApprovers bool, useStatusAvailability bool, repo *github.Repo, pr *github.PullRequest) error {
	oc, err := roc.LoadRepoOwners(repo.Owner.Login, repo.Name, pr.Base.Ref)
	if err != nil {
		return fmt.Errorf("error loading RepoOwners: %w", err)
	}

	changes, err := ghc.GetPullRequestChanges(repo.Owner.Login, repo.Name, pr.Number)
	if err != nil {
		return fmt.Errorf("error getting PR changes: %w", err)
	}

	var reviewers []string
	var requiredReviewers []string
	if reviewerCount != nil {
		reviewers, requiredReviewers, err = getReviewers(oc, ghc, log, pr.User.Login, changes, *reviewerCount, useStatusAvailability)
		if err != nil {
			return err
		}
		if missing := *reviewerCount - len(reviewers); missing > 0 {
			if !excludeApprovers {
				// Attempt to use approvers as additional reviewers. This must use
				// reviewerCount instead of missing because owners can be both reviewers
				// and approvers and the search might stop too early if it finds
				// duplicates.
				frc := fallbackReviewersClient{ownersClient: oc}
				approvers, _, err := getReviewers(frc, ghc, log, pr.User.Login, changes, *reviewerCount, useStatusAvailability)
				if err != nil {
					return err
				}
				var added int
				combinedReviewers := sets.NewString(reviewers...)
				for _, approver := range approvers {
					if !combinedReviewers.Has(approver) {
						reviewers = append(reviewers, approver)
						combinedReviewers.Insert(approver)
						added++
					}
				}
				log.Infof("Added %d approvers as reviewers. %d/%d reviewers found.", added, combinedReviewers.Len(), *reviewerCount)
			}
		}
		if missing := *reviewerCount - len(reviewers); missing > 0 {
			log.Debugf("Not enough reviewers found in OWNERS files for files touched by this PR. %d/%d reviewers found.", len(reviewers), *reviewerCount)
		}
	}

	if maxReviewers > 0 && len(reviewers) > maxReviewers {
		log.Infof("Limiting request of %d reviewers to %d maxReviewers.", len(reviewers), maxReviewers)
		reviewers = reviewers[:maxReviewers]
	}

	// add required reviewers if any
	reviewers = append(reviewers, requiredReviewers...)

	if len(reviewers) > 0 {
		log.Infof("Requesting reviews from users %s.", reviewers)
		return ghc.RequestReview(repo.Owner.Login, repo.Name, pr.Number, reviewers)
	}
	return nil
}

func getReviewers(rc reviewersClient, ghc githubClient, log *logrus.Entry, author string, files []github.PullRequestChange, minReviewers int, useStatusAvailability bool) ([]string, []string, error) {
	authorSet := sets.NewString(github.NormLogin(author))
	reviewers := layeredsets.NewString()
	requiredReviewers := sets.NewString()
	leafReviewers := layeredsets.NewString()
	busyReviewers := sets.NewString()
	ownersSeen := sets.NewString()
	if minReviewers == 0 {
		return reviewers.List(), requiredReviewers.List(), nil
	}
	// first build 'reviewers' by taking a unique reviewer from each OWNERS file.
	for _, file := range files {
		ownersFile := rc.FindReviewersOwnersForFile(file.Filename)
		if ownersSeen.Has(ownersFile) {
			continue
		}
		ownersSeen.Insert(ownersFile)

		// record required reviewers if any
		requiredReviewers.Insert(rc.RequiredReviewers(file.Filename).UnsortedList()...)

		fileUnusedLeafs := layeredsets.NewString(rc.LeafReviewers(file.Filename).List()...).Difference(reviewers.Set()).Difference(authorSet)
		if fileUnusedLeafs.Len() == 0 {
			continue
		}
		leafReviewers = leafReviewers.Union(fileUnusedLeafs)
		if r := findReviewer(ghc, log, useStatusAvailability, &busyReviewers, &fileUnusedLeafs); r != "" {
			reviewers.Insert(0, r)
		}
	}
	// now ensure that we request review from at least minReviewers reviewers. Favor leaf reviewers.
	unusedLeafs := leafReviewers.Difference(reviewers.Set())
	for reviewers.Len() < minReviewers && unusedLeafs.Len() > 0 {
		if r := findReviewer(ghc, log, useStatusAvailability, &busyReviewers, &unusedLeafs); r != "" {
			reviewers.Insert(1, r)
		}
	}
	for _, file := range files {
		if reviewers.Len() >= minReviewers {
			break
		}
		fileReviewers := rc.Reviewers(file.Filename).Difference(authorSet)
		for reviewers.Len() < minReviewers && fileReviewers.Len() > 0 {
			if r := findReviewer(ghc, log, useStatusAvailability, &busyReviewers, &fileReviewers); r != "" {
				reviewers.Insert(2, r)
			}
		}
	}
	return reviewers.List(), requiredReviewers.List(), nil
}

// findReviewer finds a reviewer from a set, potentially using status
// availability.
func findReviewer(ghc githubClient, log *logrus.Entry, useStatusAvailability bool, busyReviewers *sets.String, targetSet *layeredsets.String) string {
	// if we don't care about status availability, just pop a target from the set
	if !useStatusAvailability {
		return targetSet.PopRandom()
	}

	// if we do care, start looping through the candidates
	for {
		if targetSet.Len() == 0 {
			// if there are no candidates left, then break
			break
		}
		candidate := targetSet.PopRandom()
		if busyReviewers.Has(candidate) {
			// we've already verified this reviewer is busy
			continue
		}
		busy, err := isUserBusy(ghc, candidate)
		if err != nil {
			log.Errorf("error checking user availability: %v", err)
		}
		if !busy {
			return candidate
		}
		// if we haven't returned the candidate, then they must be busy.
		busyReviewers.Insert(candidate)
	}
	return ""
}

type githubAvailabilityQuery struct {
	User struct {
		Login  githubql.String
		Status struct {
			IndicatesLimitedAvailability githubql.Boolean
		}
	} `graphql:"user(login: $user)"`
}

func isUserBusy(ghc githubClient, user string) (bool, error) {
	var query githubAvailabilityQuery
	vars := map[string]interface{}{
		"user": githubql.String(user),
	}
	ctx := context.Background()
	err := ghc.Query(ctx, &query, vars)
	return bool(query.User.Status.IndicatesLimitedAvailability), err
}
<commit_msg>Improve logging in blunderbuss<commit_after>/*
Copyright 2017 The Kubernetes Authors.

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

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

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

package blunderbuss

import (
	"context"
	"fmt"
	"regexp"

	githubql "github.com/shurcooL/githubv4"
	"github.com/sirupsen/logrus"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/test-infra/prow/pkg/layeredsets"

	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/github"
	"k8s.io/test-infra/prow/pluginhelp"
	"k8s.io/test-infra/prow/plugins"
	"k8s.io/test-infra/prow/plugins/assign"
	"k8s.io/test-infra/prow/repoowners"
)

const (
	// PluginName defines this plugin's registered name.
	PluginName = "blunderbuss"
)

var (
	match = regexp.MustCompile(`(?mi)^/auto-cc\s*$`)
)

func init() {
	plugins.RegisterPullRequestHandler(PluginName, handlePullRequestEvent, helpProvider)
	plugins.RegisterGenericCommentHandler(PluginName, handleGenericCommentEvent, helpProvider)
}

func configString(reviewCount int) string {
	var pluralSuffix string
	if reviewCount > 1 {
		pluralSuffix = "s"
	}
	return fmt.Sprintf("Blunderbuss is currently configured to request reviews from %d reviewer%s.", reviewCount, pluralSuffix)
}

func helpProvider(config *plugins.Configuration, _ []config.OrgRepo) (*pluginhelp.PluginHelp, error) {
	var reviewCount int
	if config.Blunderbuss.ReviewerCount != nil {
		reviewCount = *config.Blunderbuss.ReviewerCount
	}
	two := 2
	yamlSnippet, err := plugins.CommentMap.GenYaml(&plugins.Configuration{
		Blunderbuss: plugins.Blunderbuss{
			ReviewerCount:         &two,
			MaxReviewerCount:      3,
			ExcludeApprovers:      true,
			UseStatusAvailability: true,
		},
	})
	if err != nil {
		logrus.WithError(err).Warnf("cannot generate comments for %s plugin", PluginName)
	}
	pluginHelp := &pluginhelp.PluginHelp{
		Description: "The blunderbuss plugin automatically requests reviews from reviewers when a new PR is created. The reviewers are selected based on the reviewers specified in the OWNERS files that apply to the files modified by the PR.",
		Config: map[string]string{
			"": configString(reviewCount),
		},
		Snippet: yamlSnippet,
	}
	pluginHelp.AddCommand(pluginhelp.Command{
		Usage:       "/auto-cc",
		Featured:    false,
		Description: "Manually request reviews from reviewers for a PR. Useful if OWNERS file were updated since the PR was opened.",
		Examples:    []string{"/auto-cc"},
		WhoCanUse:   "Anyone",
	})
	return pluginHelp, nil
}

type reviewersClient interface {
	FindReviewersOwnersForFile(path string) string
	Reviewers(path string) layeredsets.String
	RequiredReviewers(path string) sets.String
	LeafReviewers(path string) sets.String
}

type ownersClient interface {
	reviewersClient
	FindApproverOwnersForFile(path string) string
	Approvers(path string) layeredsets.String
	LeafApprovers(path string) sets.String
}

type fallbackReviewersClient struct {
	ownersClient
}

func (foc fallbackReviewersClient) FindReviewersOwnersForFile(path string) string {
	return foc.ownersClient.FindApproverOwnersForFile(path)
}

func (foc fallbackReviewersClient) Reviewers(path string) layeredsets.String {
	return foc.ownersClient.Approvers(path)
}

func (foc fallbackReviewersClient) LeafReviewers(path string) sets.String {
	return foc.ownersClient.LeafApprovers(path)
}

type githubClient interface {
	RequestReview(org, repo string, number int, logins []string) error
	GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error)
	GetPullRequest(org, repo string, number int) (*github.PullRequest, error)
	Query(context.Context, interface{}, map[string]interface{}) error
}

type repoownersClient interface {
	LoadRepoOwners(org, repo, base string) (repoowners.RepoOwner, error)
}

func handlePullRequestEvent(pc plugins.Agent, pre github.PullRequestEvent) error {
	return handlePullRequest(
		pc.GitHubClient,
		pc.OwnersClient,
		pc.Logger,
		pc.PluginConfig.Blunderbuss,
		pre.Action,
		&pre.PullRequest,
		&pre.Repo,
	)
}

func handlePullRequest(ghc githubClient, roc repoownersClient, log *logrus.Entry, config plugins.Blunderbuss, action github.PullRequestEventAction, pr *github.PullRequest, repo *github.Repo) error {
	if action != github.PullRequestActionOpened || assign.CCRegexp.MatchString(pr.Body) {
		return nil
	}

	return handle(
		ghc,
		roc,
		log,
		config.ReviewerCount,
		config.MaxReviewerCount,
		config.ExcludeApprovers,
		config.UseStatusAvailability,
		repo,
		pr,
	)
}

func handleGenericCommentEvent(pc plugins.Agent, ce github.GenericCommentEvent) error {
	return handleGenericComment(
		pc.GitHubClient,
		pc.OwnersClient,
		pc.Logger,
		pc.PluginConfig.Blunderbuss,
		ce.Action,
		ce.IsPR,
		ce.Number,
		ce.IssueState,
		&ce.Repo,
		ce.Body,
	)
}

func handleGenericComment(ghc githubClient, roc repoownersClient, log *logrus.Entry, config plugins.Blunderbuss, action github.GenericCommentEventAction, isPR bool, prNumber int, issueState string, repo *github.Repo, body string) error {
	if action != github.GenericCommentActionCreated || !isPR || issueState == "closed" {
		return nil
	}

	if !match.MatchString(body) {
		return nil
	}

	pr, err := ghc.GetPullRequest(repo.Owner.Login, repo.Name, prNumber)
	if err != nil {
		return fmt.Errorf("error loading PullRequest: %w", err)
	}

	return handle(
		ghc,
		roc,
		log,
		config.ReviewerCount,
		config.MaxReviewerCount,
		config.ExcludeApprovers,
		config.UseStatusAvailability,
		repo,
		pr,
	)
}

func handle(ghc githubClient, roc repoownersClient, log *logrus.Entry, reviewerCount *int, maxReviewers int, excludeApprovers bool, useStatusAvailability bool, repo *github.Repo, pr *github.PullRequest) error {
	oc, err := roc.LoadRepoOwners(repo.Owner.Login, repo.Name, pr.Base.Ref)
	if err != nil {
		return fmt.Errorf("error loading RepoOwners: %w", err)
	}

	changes, err := ghc.GetPullRequestChanges(repo.Owner.Login, repo.Name, pr.Number)
	if err != nil {
		return fmt.Errorf("error getting PR changes: %w", err)
	}

	var reviewers []string
	var requiredReviewers []string
	if reviewerCount != nil {
		reviewers, requiredReviewers, err = getReviewers(oc, ghc, log, pr.User.Login, changes, *reviewerCount, useStatusAvailability)
		if err != nil {
			return err
		}
		if missing := *reviewerCount - len(reviewers); missing > 0 {
			if !excludeApprovers {
				// Attempt to use approvers as additional reviewers. This must use
				// reviewerCount instead of missing because owners can be both reviewers
				// and approvers and the search might stop too early if it finds
				// duplicates.
				frc := fallbackReviewersClient{ownersClient: oc}
				approvers, _, err := getReviewers(frc, ghc, log, pr.User.Login, changes, *reviewerCount, useStatusAvailability)
				if err != nil {
					return err
				}
				var added int
				combinedReviewers := sets.NewString(reviewers...)
				for _, approver := range approvers {
					if !combinedReviewers.Has(approver) {
						reviewers = append(reviewers, approver)
						combinedReviewers.Insert(approver)
						added++
					}
				}
				log.Infof("Added %d approvers as reviewers. %d/%d reviewers found.", added, combinedReviewers.Len(), *reviewerCount)
			}
		}
		if missing := *reviewerCount - len(reviewers); missing > 0 {
			log.Debugf("Not enough reviewers found in OWNERS files for files touched by this PR. %d/%d reviewers found.", len(reviewers), *reviewerCount)
		}
	}

	if maxReviewers > 0 && len(reviewers) > maxReviewers {
		log.Infof("Limiting request of %d reviewers to %d maxReviewers.", len(reviewers), maxReviewers)
		reviewers = reviewers[:maxReviewers]
	}

	// add required reviewers if any
	reviewers = append(reviewers, requiredReviewers...)

	if len(reviewers) > 0 {
		log.Infof("Requesting reviews from users %s.", reviewers)
		return ghc.RequestReview(repo.Owner.Login, repo.Name, pr.Number, reviewers)
	}
	return nil
}

func getReviewers(rc reviewersClient, ghc githubClient, log *logrus.Entry, author string, files []github.PullRequestChange, minReviewers int, useStatusAvailability bool) ([]string, []string, error) {
	authorSet := sets.NewString(github.NormLogin(author))
	reviewers := layeredsets.NewString()
	requiredReviewers := sets.NewString()
	leafReviewers := layeredsets.NewString()
	busyReviewers := sets.NewString()
	ownersSeen := sets.NewString()
	if minReviewers == 0 {
		return reviewers.List(), requiredReviewers.List(), nil
	}
	// first build 'reviewers' by taking a unique reviewer from each OWNERS file.
	for _, file := range files {
		ownersFile := rc.FindReviewersOwnersForFile(file.Filename)
		if ownersSeen.Has(ownersFile) {
			continue
		}
		ownersSeen.Insert(ownersFile)

		// record required reviewers if any
		requiredReviewers.Insert(rc.RequiredReviewers(file.Filename).UnsortedList()...)

		fileUnusedLeafs := layeredsets.NewString(rc.LeafReviewers(file.Filename).List()...).Difference(reviewers.Set()).Difference(authorSet)
		if fileUnusedLeafs.Len() == 0 {
			continue
		}
		leafReviewers = leafReviewers.Union(fileUnusedLeafs)
		if r := findReviewer(ghc, log, useStatusAvailability, &busyReviewers, &fileUnusedLeafs); r != "" {
			reviewers.Insert(0, r)
		}
	}
	// now ensure that we request review from at least minReviewers reviewers. Favor leaf reviewers.
	unusedLeafs := leafReviewers.Difference(reviewers.Set())
	for reviewers.Len() < minReviewers && unusedLeafs.Len() > 0 {
		if r := findReviewer(ghc, log, useStatusAvailability, &busyReviewers, &unusedLeafs); r != "" {
			reviewers.Insert(1, r)
		}
	}
	for _, file := range files {
		if reviewers.Len() >= minReviewers {
			break
		}
		fileReviewers := rc.Reviewers(file.Filename).Difference(authorSet)
		for reviewers.Len() < minReviewers && fileReviewers.Len() > 0 {
			if r := findReviewer(ghc, log, useStatusAvailability, &busyReviewers, &fileReviewers); r != "" {
				reviewers.Insert(2, r)
			}
		}
	}
	return reviewers.List(), requiredReviewers.List(), nil
}

// findReviewer finds a reviewer from a set, potentially using status
// availability.
func findReviewer(ghc githubClient, log *logrus.Entry, useStatusAvailability bool, busyReviewers *sets.String, targetSet *layeredsets.String) string {
	// if we don't care about status availability, just pop a target from the set
	if !useStatusAvailability {
		return targetSet.PopRandom()
	}

	// if we do care, start looping through the candidates
	for {
		if targetSet.Len() == 0 {
			// if there are no candidates left, then break
			break
		}
		candidate := targetSet.PopRandom()
		if busyReviewers.Has(candidate) {
			// we've already verified this reviewer is busy
			continue
		}
		busy, err := isUserBusy(ghc, candidate)
		if err != nil {
			log.WithField("user", candidate).WithError(err).Error("Error checking user availability")
		}
		if !busy {
			return candidate
		}
		// if we haven't returned the candidate, then they must be busy.
		log.WithField("user", candidate).Debug("User marked as a busy reviewer")
		busyReviewers.Insert(candidate)
	}
	return ""
}

type githubAvailabilityQuery struct {
	User struct {
		Login  githubql.String
		Status struct {
			IndicatesLimitedAvailability githubql.Boolean
		}
	} `graphql:"user(login: $user)"`
}

func isUserBusy(ghc githubClient, user string) (bool, error) {
	var query githubAvailabilityQuery
	vars := map[string]interface{}{
		"user": githubql.String(user),
	}
	ctx := context.Background()
	err := ghc.Query(ctx, &query, vars)
	return bool(query.User.Status.IndicatesLimitedAvailability), err
}
<|endoftext|>


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

package swarmingimpl

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"

	"google.golang.org/api/googleapi"

	"github.com/maruel/subcommands"

	"go.chromium.org/luci/common/errors"
	"go.chromium.org/luci/common/flag"
	"go.chromium.org/luci/common/flag/stringmapflag"
	"go.chromium.org/luci/common/system/signals"
)

// CmdBots returns an object for the `bots` subcommand.
func CmdBots(authFlags AuthFlags) *subcommands.Command {
	return &subcommands.Command{
		UsageLine: "bots <options>",
		ShortDesc: "lists bots",
		LongDesc:  "List bots matching the given options.",
		CommandRun: func() subcommands.CommandRun {
			r := &botsRun{}
			r.Init(authFlags)
			return r
		},
	}
}

type botsRun struct {
	commonFlags
	outfile    string
	dimensions stringmapflag.Value
	fields     []googleapi.Field
	count      bool
}

func (b *botsRun) Init(authFlags AuthFlags) {
	b.commonFlags.Init(authFlags)
	b.Flags.StringVar(&b.outfile, "json", "", "Path to output JSON results. Implies quiet.")
	b.Flags.Var(&b.dimensions, "dimension", "Dimension to select the right kind of bot. In the form of `key=value`")
	b.Flags.Var(flag.FieldSlice(&b.fields), "field", "Fields to include in a partial response. May be repeated.")
	b.Flags.BoolVar(&b.count, "count", false, "Report the count of bots instead of listing them.")
}

func (b *botsRun) Parse() error {
	if err := b.commonFlags.Parse(); err != nil {
		return err
	}
	if b.defaultFlags.Quiet && b.outfile == "" {
		return errors.Reason("specify -json when using -quiet").Err()
	}
	if b.outfile != "" {
		b.defaultFlags.Quiet = true
	}
	if b.count && len(b.fields) > 0 {
		return errors.Reason("-field cannot be used with -count").Err()
	}
	return nil
}

func (b *botsRun) main(_ subcommands.Application) error {
	ctx, cancel := context.WithCancel(b.defaultFlags.MakeLoggingContext(os.Stderr))
	defer cancel()
	defer signals.HandleInterrupt(cancel)()
	service, err := b.createSwarmingClient(ctx)
	if err != nil {
		return err
	}

	dims := make([]string, 0, len(b.dimensions))
	for k, v := range b.dimensions {
		dims = append(dims, k+":"+v)
	}

	var data interface{}
	if b.count {
		data, err = service.CountBots(ctx, dims...)
		if err != nil {
			return err
		}
	} else {
		data, err = service.ListBots(ctx, dims, b.fields)
		if err != nil {
			return err
		}
	}

	if !b.defaultFlags.Quiet {
		j, err := json.MarshalIndent(data, "", " ")
		if err != nil {
			return err
		}
		fmt.Printf("%s\n", j)
	}
	if b.outfile != "" {
		j, err := json.Marshal(data)
		if err != nil {
			return err
		}
		if err := ioutil.WriteFile(b.outfile, j, 0644); err != nil {
			return err
		}
	}
	return nil
}

func (b *botsRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {
	if len(args) != 0 {
		fmt.Fprintf(a.GetErr(), "%s: unknown args: %s\n", a.GetName(), args)
		return 1
	}
	if err := b.Parse(); err != nil {
		fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
		return 1
	}
	if err := b.main(a); err != nil {
		fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
		return 1
	}
	return 0
}
<commit_msg>swarming: add link to explanation of field flag<commit_after>// Copyright 2018 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package swarmingimpl

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"

	"google.golang.org/api/googleapi"

	"github.com/maruel/subcommands"

	"go.chromium.org/luci/common/errors"
	"go.chromium.org/luci/common/flag"
	"go.chromium.org/luci/common/flag/stringmapflag"
	"go.chromium.org/luci/common/system/signals"
)

// CmdBots returns an object for the `bots` subcommand.
func CmdBots(authFlags AuthFlags) *subcommands.Command {
	return &subcommands.Command{
		UsageLine: "bots <options>",
		ShortDesc: "lists bots",
		LongDesc:  "List bots matching the given options.",
		CommandRun: func() subcommands.CommandRun {
			r := &botsRun{}
			r.Init(authFlags)
			return r
		},
	}
}

type botsRun struct {
	commonFlags
	outfile    string
	dimensions stringmapflag.Value
	fields     []googleapi.Field
	count      bool
}

func (b *botsRun) Init(authFlags AuthFlags) {
	b.commonFlags.Init(authFlags)
	b.Flags.StringVar(&b.outfile, "json", "", "Path to output JSON results. Implies quiet.")
	b.Flags.Var(&b.dimensions, "dimension", "Dimension to select the right kind of bot. In the form of `key=value`")
	b.Flags.Var(flag.FieldSlice(&b.fields), "field", `Fields to include in a partial response. May be repeated.
See https://pkg.go.dev/google.golang.org/api/googleapi#Field for more explanation`)
	b.Flags.BoolVar(&b.count, "count", false, "Report the count of bots instead of listing them.")
}

func (b *botsRun) Parse() error {
	if err := b.commonFlags.Parse(); err != nil {
		return err
	}
	if b.defaultFlags.Quiet && b.outfile == "" {
		return errors.Reason("specify -json when using -quiet").Err()
	}
	if b.outfile != "" {
		b.defaultFlags.Quiet = true
	}
	if b.count && len(b.fields) > 0 {
		return errors.Reason("-field cannot be used with -count").Err()
	}
	return nil
}

func (b *botsRun) main(_ subcommands.Application) error {
	ctx, cancel := context.WithCancel(b.defaultFlags.MakeLoggingContext(os.Stderr))
	defer cancel()
	defer signals.HandleInterrupt(cancel)()
	service, err := b.createSwarmingClient(ctx)
	if err != nil {
		return err
	}

	dims := make([]string, 0, len(b.dimensions))
	for k, v := range b.dimensions {
		dims = append(dims, k+":"+v)
	}

	var data interface{}
	if b.count {
		data, err = service.CountBots(ctx, dims...)
		if err != nil {
			return err
		}
	} else {
		data, err = service.ListBots(ctx, dims, b.fields)
		if err != nil {
			return err
		}
	}

	if !b.defaultFlags.Quiet {
		j, err := json.MarshalIndent(data, "", " ")
		if err != nil {
			return err
		}
		fmt.Printf("%s\n", j)
	}
	if b.outfile != "" {
		j, err := json.Marshal(data)
		if err != nil {
			return err
		}
		if err := ioutil.WriteFile(b.outfile, j, 0644); err != nil {
			return err
		}
	}
	return nil
}

func (b *botsRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {
	if len(args) != 0 {
		fmt.Fprintf(a.GetErr(), "%s: unknown args: %s\n", a.GetName(), args)
		return 1
	}
	if err := b.Parse(); err != nil {
		fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
		return 1
	}
	if err := b.main(a); err != nil {
		fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
		return 1
	}
	return 0
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"encoding/json"
	"github.com/bitly/go-nsq"
	"io"
	"log"
	"net"
	"strings"
	"sync"
	"time"
)

type StreamServer struct {
	*Setting
	exitChan    chan int
	msgChan     chan []byte
	recoverChan chan string
	wg          sync.WaitGroup
}

func (s *StreamServer) Run() {
	for i := 0; i < s.WritePoolSize; i++ {
		w := nsq.NewWriter(s.NsqdAddr)
		go s.writeLoop(w)
	}
	go s.readUDP()
	go s.readTCP()
	go s.recoverServer()
}

func (s *StreamServer) recoverServer() {
	for {
		select {
		case sType := <-s.recoverChan:
			time.Sleep(time.Second)
			log.Println(sType, " reconnecting")
			if sType == "tcp" {
				go s.readTCP()
			}
			if sType == "udp" {
				go s.readUDP()
			}
		case <-s.exitChan:
			return
		}
	}
}

func (s *StreamServer) writeLoop(w *nsq.Writer) {
	for {
		select {
		case msg := <-s.msgChan:
			w.Publish(s.Topic, msg)
		case <-s.exitChan:
			return
		}
	}
}
func (s *StreamServer) Stop() {
	close(s.exitChan)
	s.wg.Wait()
}

func (s *StreamServer) readUDP() {
	udpAddr, err := net.ResolveUDPAddr("udp", s.UdpPort)
	if err != nil {
		log.Fatal("udp:", err)
	}
	server, err := net.ListenUDP("udp", udpAddr)
	if err != nil {
		log.Fatal("server bind failed:", err)
	}
	defer server.Close()
	buf := make([]byte, 8192)
	for {
		select {
		case <-s.exitChan:
			return
		default:
			size, addr, err := server.ReadFromUDP(buf)
			if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
				go func() { s.recoverChan <- "udp" }()
				return
			}
			if err == io.EOF {
				go func() { s.recoverChan <- "udp" }()
				return
			}
			if err != nil {
				log.Println("read log failed", err)
				continue
			}
			body, err := logToJSON(addr.String(), string(buf[:size]))
			if err != nil {
				log.Println("failed to parser JSON", err)
				continue
			}
			s.msgChan <- body
		}
	}
}
func (s *StreamServer) readTCP() {
	server, err := net.Listen("tcp", s.TcpPort)
	if err != nil {
		log.Fatal("server bind failed:", err)
	}
	defer server.Close()
	for {
		select {
		case <-s.exitChan:
			return
		default:
			fd, err := server.Accept()
			if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
				go func() { s.recoverChan <- "tcp" }()
				return
			}
			if err != nil {
				log.Fatal("accept error", err)
				time.Sleep(time.Second)
			} else {
				go s.loghandle(fd)
			}
		}
	}
}

// receive log from tcp socket, encode json and send to msg_chan
func (s *StreamServer) loghandle(fd net.Conn) {
	defer fd.Close()
	rbuf := bufio.NewReader(fd)
	addr := fd.RemoteAddr()
	s.wg.Add(1)
	defer s.wg.Done()
	for {
		select {
		case <-s.exitChan:
			return
		default:
			msg, err := rbuf.ReadString('\n')
			if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
				return
			}
			if err == io.EOF {
				return
			}
			if err != nil {
				log.Println("read log failed", err)
				continue
			}
			body, err := logToJSON(addr.String(), msg)
			if err != nil {
				log.Println("failed to parser JSON", err)
				continue
			}
			s.msgChan <- body
		}
	}
}

func logToJSON(addr string, msg string) ([]byte, error) {
	r := make(map[string]string)
	r["from"] = addr
	r["raw_msg"] = msg
	return json.Marshal(r)
}
<commit_msg>go-nsq 1.0<commit_after>package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"github.com/bitly/go-nsq"
	"io"
	"log"
	"net"
	"os"
	"strings"
	"sync"
	"time"
)

type StreamServer struct {
	*Setting
	exitChan    chan int
	msgChan     chan []byte
	recoverChan chan string
	wg          sync.WaitGroup
}

func (s *StreamServer) Run() {
	cfg := nsq.NewConfig()
	hostname, _ := os.Hostname()
	cfg.Set("user_agent", fmt.Sprintf("netstream/%s", hostname))
	cfg.Set("snappy", true)
	for i := 0; i < s.WritePoolSize; i++ {
		w, _ := nsq.NewProducer(s.NsqdAddr, cfg)
		go s.writeLoop(w)
	}
	go s.readUDP()
	go s.readTCP()
	go s.recoverServer()
}

func (s *StreamServer) recoverServer() {
	for {
		select {
		case sType := <-s.recoverChan:
			time.Sleep(time.Second)
			log.Println(sType, " reconnecting")
			if sType == "tcp" {
				go s.readTCP()
			}
			if sType == "udp" {
				go s.readUDP()
			}
		case <-s.exitChan:
			return
		}
	}
}

func (s *StreamServer) writeLoop(w *nsq.Producer) {
	for {
		select {
		case msg := <-s.msgChan:
			w.Publish(s.Topic, msg)
		case <-s.exitChan:
			return
		}
	}
}
func (s *StreamServer) Stop() {
	close(s.exitChan)
	s.wg.Wait()
}

func (s *StreamServer) readUDP() {
	udpAddr, err := net.ResolveUDPAddr("udp", s.UdpPort)
	if err != nil {
		log.Fatal("udp:", err)
	}
	server, err := net.ListenUDP("udp", udpAddr)
	if err != nil {
		log.Fatal("server bind failed:", err)
	}
	defer server.Close()
	buf := make([]byte, 8192)
	for {
		select {
		case <-s.exitChan:
			return
		default:
			size, addr, err := server.ReadFromUDP(buf)
			if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
				go func() { s.recoverChan <- "udp" }()
				return
			}
			if err == io.EOF {
				go func() { s.recoverChan <- "udp" }()
				return
			}
			if err != nil {
				log.Println("read log failed", err)
				continue
			}
			body, err := logToJSON(addr.String(), string(buf[:size]))
			if err != nil {
				log.Println("failed to parser JSON", err)
				continue
			}
			s.msgChan <- body
		}
	}
}
func (s *StreamServer) readTCP() {
	server, err := net.Listen("tcp", s.TcpPort)
	if err != nil {
		log.Fatal("server bind failed:", err)
	}
	defer server.Close()
	for {
		select {
		case <-s.exitChan:
			return
		default:
			fd, err := server.Accept()
			if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
				go func() { s.recoverChan <- "tcp" }()
				return
			}
			if err != nil {
				log.Fatal("accept error", err)
				time.Sleep(time.Second)
			} else {
				go s.loghandle(fd)
			}
		}
	}
}

// receive log from tcp socket, encode json and send to msg_chan
func (s *StreamServer) loghandle(fd net.Conn) {
	defer fd.Close()
	rbuf := bufio.NewReader(fd)
	addr := fd.RemoteAddr()
	s.wg.Add(1)
	defer s.wg.Done()
	for {
		select {
		case <-s.exitChan:
			return
		default:
			msg, err := rbuf.ReadString('\n')
			if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
				return
			}
			if err == io.EOF {
				return
			}
			if err != nil {
				log.Println("read log failed", err)
				continue
			}
			body, err := logToJSON(addr.String(), msg)
			if err != nil {
				log.Println("failed to parser JSON", err)
				continue
			}
			s.msgChan <- body
		}
	}
}

func logToJSON(addr string, msg string) ([]byte, error) {
	r := make(map[string]string)
	r["from"] = addr
	r["raw_msg"] = msg
	return json.Marshal(r)
}
<|endoftext|>