<commit_before>package b2

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

// TODO replace with parseCreateB2Response test
func Test_CreateB2_Errors(t *testing.T) {
	codes, bodies := errorResponses()
	for i := range codes {
		s, c := setupRequest(codes[i], bodies[i])

		client := &client{Protocol: "http", Client: c}
		b, err := createB2("1", "1", client)
		testErrorResponse(err, codes[i], t)
		if b != nil {
			t.Errorf("Expected b to be empty, instead got %+v", b)
		}

		s.Close()
	}
}

func Test_createB2_HasAuth(t *testing.T) {
	reqChan := make(chan *http.Request, 1)
	s, c := setupMockJsonServer(200, "", reqChan)
	defer s.Close()

	client := &client{Protocol: "http", Client: c}

	createB2("1", "1", client)

	// get the request that the mock server received
	req := <-reqChan

	username, password, ok := req.BasicAuth()
	if !ok {
		t.Fatal("Expected ok to be true, instead got false")
	}
	if username != "1" {
		t.Errorf(`Expected username to be "1", instead got %s`, username)
	}
	if password != "1" {
		t.Errorf(`Expected password to be "1", instead got %s`, password)
	}
}

func Test_parseCreateB2Response(t *testing.T) {
	resp := &http.Response{
		StatusCode: 200,
		Body: nopCloser{
			strings.NewReader(`{"accountId":"1","authorizationToken":"1","apiUrl":"/","downloadUrl":"/"}`)},
	}

	b := &B2{AccountID: "1", ApplicationKey: "key"}
	b, err := b.parseCreateB2Response(resp)
	if err != nil {
		t.Fatalf("Expected err to be nil, instead got %+v", err)
	}

	if b.AccountID != "1" {
		t.Errorf(`Expected AccountID to be "1", instead got %s`, b.AccountID)
	}
	if b.AuthorizationToken != "1" {
		t.Errorf(`Expected AuthorizationToken to be "1", instead got %s`, b.AuthorizationToken)
	}
	if b.ApiUrl != "/" {
		t.Errorf(`Expected ApiUrl to be "/", instead got %s`, b.ApiUrl)
	}
	if b.DownloadUrl != "/" {
		t.Errorf(`Expected DownloadUrl to be "/", instead got %s`, b.DownloadUrl)
	}
}

func Test_B2_CreateRequest(t *testing.T) {
	b2 := &B2{client: &client{Protocol: "https"}} // set client protocol to default

	methods := []string{
		"GET", "POST", "KITTENS",
		"POST", "BAD METHOD",
	}
	urls := []string{
		"http://example.com", "kittens://example.com", "aoeu://example.com",
		"invalid-url", "http://example.com",
	}
	reqBody := struct {
		a int `json:"a"`
	}{a: 1}

	for i := 0; i < 3; i++ {
		req, err := b2.CreateRequest(methods[i], urls[i], reqBody)
		if err != nil {
			t.Fatalf("Expected err to be nil, instead got %+v", err)
		}
		if req.URL.Scheme != "https" {
			t.Errorf(`Expected url protocol to be "https", instead got %s`, req.URL.Scheme)
		}
		if req.Body == nil {
			t.Error("Expected req.Body to not be nil")
		}
	}
	for i := 3; i < 5; i++ {
		req, err := b2.CreateRequest(methods[i], urls[i], reqBody)
		if req != nil {
			t.Errorf("Expected req to be nil, instead got %+v", req)
		}
		if err == nil {
			t.Fatal("Expected err to exist")
		}
	}
}

func Test_replaceProtocol(t *testing.T) {
	b2s := []B2{
		B2{client: &client{Protocol: "https"}},
		B2{client: &client{Protocol: "http"}},
		B2{client: &client{Protocol: "kittens"}},
	}
	urls := []string{
		"http://localhost", "https://localhost", "http://localhost", "kittens://localhost",
		"https://www.backblaze.com/", "https://www.backblaze.com/",
		"http://www.backblaze.com/", "kittens://www.backblaze.com/",
		"non/url/",
	}

	for i, b := range b2s {
		index, i2, index2 := i+1, i+4, i+5 // make offsets
		// localhost
		url, err := b.replaceProtocol(urls[i])
		if err != nil {
			t.Errorf("Expected no error, instead got %+v", err)
		}
		if url != urls[index] {
			t.Errorf("Expected url to be %s, instead got %s", urls[index], url)
		}

		// www.backblaze.com
		url, err = b.replaceProtocol(urls[i2])
		if err != nil {
			t.Errorf("Expected no error, instead got %+v", err)
		}
		if url != urls[index2] {
			t.Errorf("Expected url to be %s, instead got %s", urls[index2], url)
		}
	}

	url, err := b2s[0].replaceProtocol(urls[len(urls)-1])
	if err == nil {
		t.Errorf("Expected error, instead got nil, url returned was %s", url)
	}
}

func Test_GetBzInfoHeaders(t *testing.T) {
	headers := map[string][]string{
		"Content-Type":      []string{"kittens"},
		"X-Bz-Info-kittens": []string{"yes"},
		"X-Bz-Info-thing":   []string{"one"},
	}
	resp := &http.Response{Header: headers}

	bzHeaders := GetBzInfoHeaders(resp)

	if len(bzHeaders) != 2 {
		t.Fatalf("Expected length of headers to be 2, instead got %d", len(bzHeaders))
	}
	if h, ok := bzHeaders["Content-Type"]; ok {
		t.Errorf("Expected no Content-Type, instead recieved %s", h)
	}
	if h := bzHeaders["kittens"]; h != "yes" {
		t.Errorf(`Expected kittens to be "yes", instead got %s`, h)
	}
	if h := bzHeaders["thing"]; h != "one" {
		t.Errorf(`Expected thing to be "one", instead got %s`, h)
	}
}

// TODO remove
func setupRequest(code int, body string) (*httptest.Server, http.Client) {
	return setupMockJsonServer(code, body, nil)
}

// TODO remove
func setupMockJsonServer(code int, body string, reqChan chan<- *http.Request) (*httptest.Server, http.Client) {
	headers := map[string]string{"Content-Type": "application/json"}
	return setupMockServer(code, body, headers, reqChan)
}

// TODO remove
func setupMockServer(code int, body string, headers map[string]string, reqChan chan<- *http.Request) (*httptest.Server, http.Client) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if reqChan != nil {
			reqChan <- r
		}

		for k, v := range headers {
			w.Header().Set(k, v)
		}

		w.WriteHeader(code)
		fmt.Fprintln(w, body)
	}))

	tr := &http.Transport{
		Proxy: func(req *http.Request) (*url.URL, error) {
			return url.Parse(server.URL)
		},
	}

	return server, http.Client{Transport: tr}
}

// TODO replace with non-200 *http.Response creator
func errorResponses() ([]int, []string) {
	codes := []int{400, 401}
	bodies := []string{
		`{"status":400,"code":"nope","message":"nope nope"}`,
		`{"status":401,"code":"nope","message":"nope nope"}`,
	}
	return codes, bodies
}

func testErrorResponse(err error, code int, t *testing.T) {
	if err == nil {
		t.Error("Expected error, no error received")
	} else if err.Error() != fmt.Sprintf("Status: %d, Code: nope, Message: nope nope", code) {
		t.Errorf(`Expected "Status: %d, Code: nope, Message: nope nope", instead got %s`, code, err)
	}
}

func makeTestB2(c http.Client) *B2 {
	return &B2{
		AccountID:          "id",
		AuthorizationToken: "token",
		ApiUrl:             "https://api900.backblaze.com",
		DownloadUrl:        "https://f900.backblaze.com",
		client:             &client{Protocol: "http", Client: c},
	}
}

type nopCloser struct {
	io.Reader
}

func (nopCloser) Close() error { return nil }
<commit_msg>Use ioutil's NopCloser<commit_after>package b2

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

// TODO replace with parseCreateB2Response test
func Test_CreateB2_Errors(t *testing.T) {
	codes, bodies := errorResponses()
	for i := range codes {
		s, c := setupRequest(codes[i], bodies[i])

		client := &client{Protocol: "http", Client: c}
		b, err := createB2("1", "1", client)
		testErrorResponse(err, codes[i], t)
		if b != nil {
			t.Errorf("Expected b to be empty, instead got %+v", b)
		}

		s.Close()
	}
}

func Test_createB2_HasAuth(t *testing.T) {
	reqChan := make(chan *http.Request, 1)
	s, c := setupMockJsonServer(200, "", reqChan)
	defer s.Close()

	client := &client{Protocol: "http", Client: c}

	createB2("1", "1", client)

	// get the request that the mock server received
	req := <-reqChan

	username, password, ok := req.BasicAuth()
	if !ok {
		t.Fatal("Expected ok to be true, instead got false")
	}
	if username != "1" {
		t.Errorf(`Expected username to be "1", instead got %s`, username)
	}
	if password != "1" {
		t.Errorf(`Expected password to be "1", instead got %s`, password)
	}
}

func Test_parseCreateB2Response(t *testing.T) {
	resp := &http.Response{
		StatusCode: 200,
		Body:       ioutil.NopCloser(strings.NewReader(`{"accountId":"1","authorizationToken":"1","apiUrl":"/","downloadUrl":"/"}`))}

	b := &B2{AccountID: "1", ApplicationKey: "key"}
	b, err := b.parseCreateB2Response(resp)
	if err != nil {
		t.Fatalf("Expected err to be nil, instead got %+v", err)
	}

	if b.AccountID != "1" {
		t.Errorf(`Expected AccountID to be "1", instead got %s`, b.AccountID)
	}
	if b.AuthorizationToken != "1" {
		t.Errorf(`Expected AuthorizationToken to be "1", instead got %s`, b.AuthorizationToken)
	}
	if b.ApiUrl != "/" {
		t.Errorf(`Expected ApiUrl to be "/", instead got %s`, b.ApiUrl)
	}
	if b.DownloadUrl != "/" {
		t.Errorf(`Expected DownloadUrl to be "/", instead got %s`, b.DownloadUrl)
	}
}

func Test_B2_CreateRequest(t *testing.T) {
	b2 := &B2{client: &client{Protocol: "https"}} // set client protocol to default

	methods := []string{
		"GET", "POST", "KITTENS",
		"POST", "BAD METHOD",
	}
	urls := []string{
		"http://example.com", "kittens://example.com", "aoeu://example.com",
		"invalid-url", "http://example.com",
	}
	reqBody := struct {
		a int `json:"a"`
	}{a: 1}

	for i := 0; i < 3; i++ {
		req, err := b2.CreateRequest(methods[i], urls[i], reqBody)
		if err != nil {
			t.Fatalf("Expected err to be nil, instead got %+v", err)
		}
		if req.URL.Scheme != "https" {
			t.Errorf(`Expected url protocol to be "https", instead got %s`, req.URL.Scheme)
		}
		if req.Body == nil {
			t.Error("Expected req.Body to not be nil")
		}
	}
	for i := 3; i < 5; i++ {
		req, err := b2.CreateRequest(methods[i], urls[i], reqBody)
		if req != nil {
			t.Errorf("Expected req to be nil, instead got %+v", req)
		}
		if err == nil {
			t.Fatal("Expected err to exist")
		}
	}
}

func Test_replaceProtocol(t *testing.T) {
	b2s := []B2{
		B2{client: &client{Protocol: "https"}},
		B2{client: &client{Protocol: "http"}},
		B2{client: &client{Protocol: "kittens"}},
	}
	urls := []string{
		"http://localhost", "https://localhost", "http://localhost", "kittens://localhost",
		"https://www.backblaze.com/", "https://www.backblaze.com/",
		"http://www.backblaze.com/", "kittens://www.backblaze.com/",
		"non/url/",
	}

	for i, b := range b2s {
		index, i2, index2 := i+1, i+4, i+5 // make offsets
		// localhost
		url, err := b.replaceProtocol(urls[i])
		if err != nil {
			t.Errorf("Expected no error, instead got %+v", err)
		}
		if url != urls[index] {
			t.Errorf("Expected url to be %s, instead got %s", urls[index], url)
		}

		// www.backblaze.com
		url, err = b.replaceProtocol(urls[i2])
		if err != nil {
			t.Errorf("Expected no error, instead got %+v", err)
		}
		if url != urls[index2] {
			t.Errorf("Expected url to be %s, instead got %s", urls[index2], url)
		}
	}

	url, err := b2s[0].replaceProtocol(urls[len(urls)-1])
	if err == nil {
		t.Errorf("Expected error, instead got nil, url returned was %s", url)
	}
}

func Test_GetBzInfoHeaders(t *testing.T) {
	headers := map[string][]string{
		"Content-Type":      []string{"kittens"},
		"X-Bz-Info-kittens": []string{"yes"},
		"X-Bz-Info-thing":   []string{"one"},
	}
	resp := &http.Response{Header: headers}

	bzHeaders := GetBzInfoHeaders(resp)

	if len(bzHeaders) != 2 {
		t.Fatalf("Expected length of headers to be 2, instead got %d", len(bzHeaders))
	}
	if h, ok := bzHeaders["Content-Type"]; ok {
		t.Errorf("Expected no Content-Type, instead recieved %s", h)
	}
	if h := bzHeaders["kittens"]; h != "yes" {
		t.Errorf(`Expected kittens to be "yes", instead got %s`, h)
	}
	if h := bzHeaders["thing"]; h != "one" {
		t.Errorf(`Expected thing to be "one", instead got %s`, h)
	}
}

// TODO remove
func setupRequest(code int, body string) (*httptest.Server, http.Client) {
	return setupMockJsonServer(code, body, nil)
}

// TODO remove
func setupMockJsonServer(code int, body string, reqChan chan<- *http.Request) (*httptest.Server, http.Client) {
	headers := map[string]string{"Content-Type": "application/json"}
	return setupMockServer(code, body, headers, reqChan)
}

// TODO remove
func setupMockServer(code int, body string, headers map[string]string, reqChan chan<- *http.Request) (*httptest.Server, http.Client) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if reqChan != nil {
			reqChan <- r
		}

		for k, v := range headers {
			w.Header().Set(k, v)
		}

		w.WriteHeader(code)
		fmt.Fprintln(w, body)
	}))

	tr := &http.Transport{
		Proxy: func(req *http.Request) (*url.URL, error) {
			return url.Parse(server.URL)
		},
	}

	return server, http.Client{Transport: tr}
}

// TODO replace with non-200 *http.Response creator
func errorResponses() ([]int, []string) {
	codes := []int{400, 401}
	bodies := []string{
		`{"status":400,"code":"nope","message":"nope nope"}`,
		`{"status":401,"code":"nope","message":"nope nope"}`,
	}
	return codes, bodies
}

func testErrorResponse(err error, code int, t *testing.T) {
	if err == nil {
		t.Error("Expected error, no error received")
	} else if err.Error() != fmt.Sprintf("Status: %d, Code: nope, Message: nope nope", code) {
		t.Errorf(`Expected "Status: %d, Code: nope, Message: nope nope", instead got %s`, code, err)
	}
}

func makeTestB2(c http.Client) *B2 {
	return &B2{
		AccountID:          "id",
		AuthorizationToken: "token",
		ApiUrl:             "https://api900.backblaze.com",
		DownloadUrl:        "https://f900.backblaze.com",
		client:             &client{Protocol: "http", Client: c},
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"

	"github.com/astaxie/beego"
	"github.com/sirupsen/logrus"
	"github.com/snagles/docker-registry-manager/app/models"
	_ "github.com/snagles/docker-registry-manager/app/routers"
	"github.com/urfave/cli"
)

const (
	appVersion = "3.0.2"
)

func main() {
	app := cli.NewApp()
	app.Name = "Docker Registry Manager"
	app.Usage = "Connect to, view, and manage multiple private Docker registries"

	var registriesFile, logLevel, keyPath, certPath string
	var enableHTTPS bool
	var appPort int
	app.Flags = []cli.Flag{
		cli.IntFlag{
			Name:        "port, p",
			Usage:       "port to use for the registry manager `port`",
			Value:       8080,
			Destination: &appPort,
			EnvVar:      "MANAGER_PORT",
		},
		cli.StringFlag{
			Name:        "registries, r",
			Usage:       "file location of the registries.yml `/app/registries.yml`",
			EnvVar:      "MANAGER_REGISTRIES",
			Destination: &registriesFile,
		},
		cli.StringFlag{
			Name:        "log-level, l",
			Usage:       "log-level `warn`",
			Value:       "info",
			EnvVar:      "MANAGER_LOG_LEVEL",
			Destination: &logLevel,
		},

		// Beego HTTPS options
		cli.BoolFlag{
			Name:        "enable-https, e",
			Usage:       "enable https `true or false`",
			EnvVar:      "MANAGER_ENABLE_HTTPS",
			Destination: &enableHTTPS,
		},
		cli.StringFlag{
			Name:        "tls-key, k",
			Usage:       "tls certificate path and name `/app/key.key`",
			EnvVar:      "MANAGER_KEY",
			Destination: &keyPath,
		},
		cli.StringFlag{
			Name:        "tls-certificate, cert",
			Usage:       "tls certificate path and name `/app/certificate.crt`",
			EnvVar:      "MANAGER_CERTIFICATE",
			Destination: &certPath,
		},
	}

	app.Action = func(ctx *cli.Context) {

		manager.AllRegistries.LoadConfig(registriesFile)

		err := setlevel(logLevel)
		if err != nil {
			logrus.Fatal(err)
		}

		// Beego configuration
		beego.BConfig.AppName = "docker-registry-manager"
		beego.BConfig.RunMode = "dev"
		beego.BConfig.Listen.EnableAdmin = true
		beego.BConfig.CopyRequestBody = true
		beego.BConfig.WebConfig.ViewsPath = "views"

		// set http port
		if enableHTTPS {
			beego.BConfig.Listen.HTTPSPort = appPort
			// make sure we have both key and cert
			if keyPath == "" {
				logrus.Fatal("HTTPS enabled, but no key file provided")
			} else {
				beego.BConfig.Listen.HTTPSKeyFile = keyPath
			}
			if certPath == "" {
				logrus.Fatal("HTTPS enabled, but no certificate file provided")
			} else {
				beego.BConfig.Listen.HTTPSCertFile = certPath
			}
			// if we're not using https just use standard http
		} else {
			beego.BConfig.Listen.HTTPPort = appPort
		}

		// add template functions
		beego.AddFuncMap("shortenDigest", DigestShortener)
		beego.AddFuncMap("statToSeconds", StatToSeconds)
		beego.AddFuncMap("bytefmt", ByteFmt)
		beego.AddFuncMap("bytefmtdiff", ByteDiffFmt)
		beego.AddFuncMap("timeAgo", TimeAgo)
		beego.AddFuncMap("oneIndex", func(i int) int { return i + 1 })
		beego.Run()
	}
	app.Run(os.Args)
}

func setlevel(level string) error {
	switch {
	case level == "panic":
		logrus.SetLevel(logrus.PanicLevel)
	case level == "fatal":
		logrus.SetLevel(logrus.FatalLevel)
	case level == "error":
		logrus.SetLevel(logrus.ErrorLevel)
	case level == "warn":
		logrus.SetLevel(logrus.WarnLevel)
	case level == "info":
		logrus.SetLevel(logrus.InfoLevel)
	case level == "debug":
		logrus.SetLevel(logrus.DebugLevel)
	default:
		return fmt.Errorf("Unrecognized log level: %s", level)
	}
	return nil
}
<commit_msg>Enable HTTPS config option when flag passed<commit_after>package main

import (
	"fmt"
	"os"

	"github.com/astaxie/beego"
	"github.com/sirupsen/logrus"
	"github.com/snagles/docker-registry-manager/app/models"
	_ "github.com/snagles/docker-registry-manager/app/routers"
	"github.com/urfave/cli"
)

const (
	appVersion = "3.0.2"
)

func main() {
	app := cli.NewApp()
	app.Name = "Docker Registry Manager"
	app.Usage = "Connect to, view, and manage multiple private Docker registries"

	var registriesFile, logLevel, keyPath, certPath string
	var enableHTTPS bool
	var appPort int
	app.Flags = []cli.Flag{
		cli.IntFlag{
			Name:        "port, p",
			Usage:       "port to use for the registry manager `port`",
			Value:       8080,
			Destination: &appPort,
			EnvVar:      "MANAGER_PORT",
		},
		cli.StringFlag{
			Name:        "registries, r",
			Usage:       "file location of the registries.yml `/app/registries.yml`",
			EnvVar:      "MANAGER_REGISTRIES",
			Destination: &registriesFile,
		},
		cli.StringFlag{
			Name:        "log-level, l",
			Usage:       "log-level `warn`",
			Value:       "info",
			EnvVar:      "MANAGER_LOG_LEVEL",
			Destination: &logLevel,
		},

		// Beego HTTPS options
		cli.BoolFlag{
			Name:        "enable-https, e",
			Usage:       "enable https `true or false`",
			EnvVar:      "MANAGER_ENABLE_HTTPS",
			Destination: &enableHTTPS,
		},
		cli.StringFlag{
			Name:        "tls-key, k",
			Usage:       "tls certificate path and name `/app/key.key`",
			EnvVar:      "MANAGER_KEY",
			Destination: &keyPath,
		},
		cli.StringFlag{
			Name:        "tls-certificate, cert",
			Usage:       "tls certificate path and name `/app/certificate.crt`",
			EnvVar:      "MANAGER_CERTIFICATE",
			Destination: &certPath,
		},
	}

	app.Action = func(ctx *cli.Context) {

		manager.AllRegistries.LoadConfig(registriesFile)

		err := setlevel(logLevel)
		if err != nil {
			logrus.Fatal(err)
		}

		// Beego configuration
		beego.BConfig.AppName = "docker-registry-manager"
		beego.BConfig.RunMode = "dev"
		beego.BConfig.Listen.EnableAdmin = true
		beego.BConfig.CopyRequestBody = true
		beego.BConfig.WebConfig.ViewsPath = "views"

		// set http port
		if enableHTTPS {
			beego.BConfig.Listen.EnableHTTPS = true
			beego.BConfig.Listen.HTTPSPort = appPort
			// make sure we have both key and cert
			if keyPath == "" {
				logrus.Fatal("HTTPS enabled, but no key file provided")
			} else {
				beego.BConfig.Listen.HTTPSKeyFile = keyPath
			}
			if certPath == "" {
				logrus.Fatal("HTTPS enabled, but no certificate file provided")
			} else {
				beego.BConfig.Listen.HTTPSCertFile = certPath
			}
			// if we're not using https just use standard http
		} else {
			beego.BConfig.Listen.HTTPPort = appPort
		}

		// add template functions
		beego.AddFuncMap("shortenDigest", DigestShortener)
		beego.AddFuncMap("statToSeconds", StatToSeconds)
		beego.AddFuncMap("bytefmt", ByteFmt)
		beego.AddFuncMap("bytefmtdiff", ByteDiffFmt)
		beego.AddFuncMap("timeAgo", TimeAgo)
		beego.AddFuncMap("oneIndex", func(i int) int { return i + 1 })
		beego.Run()
	}
	app.Run(os.Args)
}

func setlevel(level string) error {
	switch {
	case level == "panic":
		logrus.SetLevel(logrus.PanicLevel)
	case level == "fatal":
		logrus.SetLevel(logrus.FatalLevel)
	case level == "error":
		logrus.SetLevel(logrus.ErrorLevel)
	case level == "warn":
		logrus.SetLevel(logrus.WarnLevel)
	case level == "info":
		logrus.SetLevel(logrus.InfoLevel)
	case level == "debug":
		logrus.SetLevel(logrus.DebugLevel)
	default:
		return fmt.Errorf("Unrecognized log level: %s", level)
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	x "github.com/javinc/puto"
	"github.com/javinc/puto/index"
	"github.com/javinc/puto/test"
	"github.com/javinc/puto/user"
)

// port server
const port = "8000"

func sample(c *gin.Context) {
	name := c.Param("id")
	c.String(http.StatusOK, "Hello %s", name)
}

func main() {
	router := gin.Default()

	// Routes consist of a path and a handler function.
	router.Any("/", index.Handler)
	router.Any("/test/*id", test.Handler)
	router.Any("/user/*id", user.Handler)

	// Migrates Db
	x.MySQL.AutoMigrate(
		&test.Model,
		&user.Model,
	)

	log.Println("serving on port", port)
	router.Run(":" + port)
}
<commit_msg>update gin<commit_after>package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	x "github.com/javinc/puto"
	"github.com/javinc/puto/index"
	"github.com/javinc/puto/test"
	"github.com/javinc/puto/user"
)

// port server
const port = "8000"

func sample(c *gin.Context) {
	name := c.Param("id")
	c.String(http.StatusOK, "Hello %s", name)
}

func main() {
	router := gin.New()

	// Routes consist of a path and a handler function.
	router.Any("/", index.Handler)
	router.Any("/test/*id", test.Handler)
	router.Any("/user/*id", user.Handler)

	// Migrates Db
	x.MySQL.AutoMigrate(
		&test.Model,
		&user.Model,
	)

	log.Println("serving on port", port)
	router.Run(":" + port)
}
<|endoftext|>


<commit_before>package lib

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

// TODO: finish the init template

func CreateBlog(blogName string) {
	currentPath, _ := os.Getwd()
	fmt.Println(currentPath)
	if blogName == "" {
		// ColorLog("[ERROR] Argument [blogname] is missing\n")
		os.Exit(2)
	}

	blogpath := path.Join(currentPath, blogName)
	fmt.Println(blogpath)

	fmt.Println("[INFO] Welcome to Agaue! Creating Blog...")

	os.MkdirAll(blogpath, 0775)
	fmt.Println(blogpath + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "post"), 0775)
	fmt.Println(path.Join(blogpath, "post") + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "theme"), 0775)
	fmt.Println(path.Join(blogpath, "theme") + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "config"), 0775)
	fmt.Println(path.Join(blogpath, "config") + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "test"), 0775)
	fmt.Println(path.Join(blogpath, "test") + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "public"), 0775)
	fmt.Println(path.Join(blogpath, "public") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public", "collection"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public", "collection") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public", "static"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public", "static") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "css"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "css") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "img"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "img") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "js"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "js") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "font"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "font") + string(path.Separator))
	writeFiles(path.Join(blogpath, "post", "hello-world.md"), hello)
	fmt.Println(path.Join(blogpath, "post", "hello-world.md"))
}

var hello = `
title: Hello World

##Welcome to use Agaue! Have fun~
`

func writeFiles(filename, content string) {
	f, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	f.WriteString(content)
}
<commit_msg>init.go modified<commit_after>package lib

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

// TODO: finish the init template

func CreateBlog(blogName string) {
	currentPath, _ := os.Getwd()
	fmt.Println(currentPath)
	if blogName == "" {
		// ColorLog("[ERROR] Argument [blogname] is missing\n")
		os.Exit(2)
	}

	blogpath := path.Join(currentPath, blogName)
	fmt.Println(blogpath)

	fmt.Println("[INFO] Welcome to Agaue! Creating Blog...")

	os.MkdirAll(blogpath, 0775)
	fmt.Println(blogpath + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "post"), 0775)
	fmt.Println(path.Join(blogpath, "post") + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "theme"), 0775)
	fmt.Println(path.Join(blogpath, "theme") + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "config"), 0775)
	fmt.Println(path.Join(blogpath, "config") + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "test"), 0775)
	fmt.Println(path.Join(blogpath, "test") + string(path.Separator))
	os.Mkdir(path.Join(blogpath, "public"), 0775)
	fmt.Println(path.Join(blogpath, "public") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public", "collection"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public", "collection") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public", "static"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public", "static") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "css"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "css") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "img"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "img") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "js"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "js") + string(path.Separator))
	os.Mkdir(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "font"), 0775)
	fmt.Println(path.Join(blogpath+string(path.Separator)+"public"+string(path.Separator)+"static", "font") + string(path.Separator))
	// write files include templates and markdowns
	writeFiles(path.Join(blogpath, "post", "hello-world.md"), hello)
	fmt.Println(path.Join(blogpath, "post", "hello-world.md"))
}

var hello = `
title: Hello World

##Welcome to use Agaue! Have fun~
`

func writeFiles(filename, content string) {
	f, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	f.WriteString(content)
}
<|endoftext|>


<commit_before>package app

// Average computes the average in the given audiences.
// Very basic algorithm.
func Average(audiences []Audience) int64 {
	var rv int64
	for _, a := range audiences {
		rv += int64(a.Audience)
	}
	return rv / int64(len(audiences))
}
<commit_msg>server: avoid divide by zero...<commit_after>package app

// Average computes the average in the given audiences.
// Very basic algorithm.
func Average(audiences []Audience) int64 {
	var rv int64
	for _, a := range audiences {
		rv += int64(a.Audience)
	}

	if len(audiences) == 0 {
		return 0
	}

	return rv / int64(len(audiences))
}
<|endoftext|>


<commit_before>/*
Copyright 2019 The Knative Authors

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

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

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

package activator

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"reflect"
	"strconv"
	"sync"
	"time"

	"go.uber.org/zap"
	"golang.org/x/sync/errgroup"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/types"
	corev1informers "k8s.io/client-go/informers/core/v1"
	corev1listers "k8s.io/client-go/listers/core/v1"
	"k8s.io/client-go/tools/cache"
	"knative.dev/pkg/controller"
	"knative.dev/serving/pkg/apis/networking"
	"knative.dev/serving/pkg/apis/serving"
	servinglisters "knative.dev/serving/pkg/client/listers/serving/v1alpha1"
	"knative.dev/serving/pkg/network"
	"knative.dev/serving/pkg/network/prober"
	"knative.dev/serving/pkg/queue"
	"knative.dev/serving/pkg/reconciler"
)

// RevisionDestsUpdate contains the state of healthy l4 dests for talking to a revision and is the
// primary output from the RevisionBackendsManager system. If a healthy ClusterIP is found then
// ClusterIPDest will be set to non empty string and Dests will be nil. Otherwise Dests will be set
// to a slice of healthy l4 dests for reaching the revision.
type RevisionDestsUpdate struct {
	Rev           types.NamespacedName
	ClusterIPDest string
	Dests         []string
}

const (
	probePortName  string        = "http"
	probeTimeout   time.Duration = 300 * time.Millisecond
	probeFrequency time.Duration = 200 * time.Millisecond
)

// revisionWatcher watches the podIPs and ClusterIP of the service for a revision. It implements the logic
// to supply RevisionDestsUpdate events on updateCh
type revisionWatcher struct {
	rev      types.NamespacedName
	protocol networking.ProtocolType
	updateCh chan<- *RevisionDestsUpdate

	// Stores the state of dests (podIPs) we know about
	healthStates map[string]bool
	// Stores whether the service ClusterIP has been seen as healthy
	clusterIPHealthy bool

	transport     http.RoundTripper
	destsChan     <-chan []string
	serviceLister corev1listers.ServiceLister
	logger        *zap.SugaredLogger
}

func newRevisionWatcher(rev types.NamespacedName, protocol networking.ProtocolType,
	updateCh chan<- *RevisionDestsUpdate, destsChan <-chan []string,
	transport http.RoundTripper, serviceLister corev1listers.ServiceLister,
	logger *zap.SugaredLogger) *revisionWatcher {
	return &revisionWatcher{
		rev:           rev,
		protocol:      protocol,
		updateCh:      updateCh,
		healthStates:  make(map[string]bool),
		transport:     transport,
		destsChan:     destsChan,
		serviceLister: serviceLister,
		logger:        logger,
	}
}

func filterHealthyDests(dests map[string]bool) []string {
	ret := make([]string, 0, len(dests))
	for dest, healthy := range dests {
		if healthy {
			ret = append(ret, dest)
		}
	}
	return ret
}

type destHealth struct {
	dest   string
	health bool
}

func (rw *revisionWatcher) getK8sPrivateService() (*corev1.Service, error) {
	selector := labels.SelectorFromSet(map[string]string{
		serving.RevisionLabelKey:  rw.rev.Name,
		networking.ServiceTypeKey: string(networking.ServiceTypePrivate),
	})
	svcList, err := rw.serviceLister.Services(rw.rev.Namespace).List(selector)
	if err != nil {
		return nil, err
	}

	switch len(svcList) {
	case 0:
		return nil, fmt.Errorf("found no private services for revision %q", rw.rev.String())
	case 1:
		return svcList[0], nil
	default:
		return nil, fmt.Errorf("found multiple private services matching revision %v", rw.rev)
	}
}

func (rw *revisionWatcher) probe(ctx context.Context, dest string) (bool, error) {
	httpDest := url.URL{
		Scheme: "http",
		Host:   dest,
	}
	return prober.Do(ctx, rw.transport, httpDest.String(),
		prober.WithHeader(network.ProbeHeaderName, queue.Name),
		prober.ExpectsBody(queue.Name))

}

func (rw *revisionWatcher) probeClusterIP(svc *corev1.Service) (bool, string, error) {
	if svc.Spec.ClusterIP == "" {
		return false, "", fmt.Errorf("private service %s/%s clusterIP is nil, this should never happen", svc.ObjectMeta.Namespace, svc.ObjectMeta.Name)
	}

	svcPort, ok := GetServicePort(rw.protocol, svc)
	if !ok {
		return false, "", fmt.Errorf("unable to find port in service %s/%s", svc.Namespace, svc.Name)
	}

	// Context used for our probe requests
	ctx, cancel := context.WithTimeout(context.Background(), probeTimeout)
	defer cancel()

	dest := net.JoinHostPort(svc.Spec.ClusterIP, strconv.Itoa(svcPort))
	ok, err := rw.probe(ctx, dest)
	return ok, dest, err
}

func (rw *revisionWatcher) probePodIPs(dests []string) (map[string]bool, error) {
	// Context used for our probe requests
	ctx, cancel := context.WithTimeout(context.Background(), probeTimeout)
	defer cancel()

	var probeGroup errgroup.Group
	healthStatesCh := make(chan destHealth, len(dests))

	for _, dest := range dests {
		// If the dest is already healthy then preserve that.
		if curHealthy, ok := rw.healthStates[dest]; ok && curHealthy {
			healthStatesCh <- destHealth{dest, true}
			continue
		}

		pDest := dest
		probeGroup.Go(func() error {
			ok, err := rw.probe(ctx, pDest)
			healthStatesCh <- destHealth{pDest, ok}
			return err
		})
	}

	err := probeGroup.Wait()
	close(healthStatesCh)

	healthStates := make(map[string]bool, len(dests))
	for dh := range healthStatesCh {
		healthStates[dh.dest] = dh.health
	}

	return healthStates, err
}

// checkDests performs probing and potentially sends a dests update. It is
// assumed this method is not called concurrently.
func (rw *revisionWatcher) checkDests(dests []string) {
	if len(dests) == 0 {
		if rw.clusterIPHealthy {
			// we have a healthy clusterIP but revision is not ready. We must have scaled down.
			rw.clusterIPHealthy = false

			// Send update that were now inactive
			rw.updateCh <- &RevisionDestsUpdate{Rev: rw.rev}
		}

		// We know this revision cannot be healthy so short circuit
		return
	}

	if rw.clusterIPHealthy {
		// cluster IP is healthy and we havent scaled down, short circuit
		return
	}

	// First check the clusterIP
	svc, err := rw.getK8sPrivateService()
	if err != nil {
		rw.logger.Errorw("Failed to lookup private service for revision", zap.Error(err))
		return
	}

	// If clusterIP is healthy send this update and we are done
	if ok, dest, err := rw.probeClusterIP(svc); err != nil {
		rw.logger.Errorw(fmt.Sprintf("Failed to probe clusterIP %s/%s", svc.Namespace, svc.Name), zap.Error(err))
	} else if ok {
		rw.clusterIPHealthy = true
		rw.healthStates = make(map[string]bool)
		rw.updateCh <- &RevisionDestsUpdate{Rev: rw.rev, ClusterIPDest: dest}
		return
	}

	healthStates, err := rw.probePodIPs(dests)
	if err != nil {
		rw.logger.Errorw("Failed probing", zap.Error(err))
		// We dont want to return here as an error still affects health states
	}

	rw.logger.Debugf("Done probing, got healthStates %v", healthStates)
	if !reflect.DeepEqual(rw.healthStates, healthStates) {
		rw.healthStates = healthStates
		destsArr := filterHealthyDests(healthStates)
		rw.updateCh <- &RevisionDestsUpdate{
			Rev:   rw.rev,
			Dests: destsArr,
		}
	}
}

func (rw *revisionWatcher) runWithTickCh(tickCh <-chan time.Time) {
	var dests []string
	for {
		select {
		case x, ok := <-rw.destsChan:
			if !ok {
				// shutdown
				return
			}
			dests = x
		case <-tickCh:
		}
		rw.checkDests(dests)
	}
}

func (rw *revisionWatcher) run(probeFrequency time.Duration) {
	ticker := time.NewTicker(probeFrequency)
	defer ticker.Stop()

	rw.runWithTickCh(ticker.C)
}

type revisionWatcherCh struct {
	revisionWatcher *revisionWatcher
	ch              chan []string
}

// RevisionBackendsManager listens to revision endpoints and keeps track of healthy
// l4 dests which can be used to reach a revision
type RevisionBackendsManager struct {
	revisionLister servinglisters.RevisionLister
	serviceLister  corev1listers.ServiceLister

	revisionWatchers    map[types.NamespacedName]*revisionWatcherCh
	revisionWatchersMux sync.RWMutex

	updateCh       chan<- *RevisionDestsUpdate
	transport      http.RoundTripper
	logger         *zap.SugaredLogger
	probeFrequency time.Duration
}

// NewRevisionBackendsManagerWithProbeFrequency returnes a RevisionBackendsManager that uses the supplied
// probe frequency
func NewRevisionBackendsManagerWithProbeFrequency(updateCh chan<- *RevisionDestsUpdate,
	transport http.RoundTripper, revisionLister servinglisters.RevisionLister,
	serviceLister corev1listers.ServiceLister, endpointsInformer corev1informers.EndpointsInformer,
	logger *zap.SugaredLogger, probeFrequency time.Duration) *RevisionBackendsManager {
	rbm := &RevisionBackendsManager{
		revisionLister:   revisionLister,
		serviceLister:    serviceLister,
		revisionWatchers: make(map[types.NamespacedName]*revisionWatcherCh),
		updateCh:         updateCh,
		transport:        transport,
		logger:           logger,
		probeFrequency:   probeFrequency,
	}

	endpointsInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
		FilterFunc: reconciler.ChainFilterFuncs(
			reconciler.LabelExistsFilterFunc(serving.RevisionUID),
			// We are only interested in the private services, since that is
			// what is populated by the actual revision backends.
			reconciler.LabelFilterFunc(networking.ServiceTypeKey, string(networking.ServiceTypePrivate), false),
		),
		Handler: cache.ResourceEventHandlerFuncs{
			AddFunc:    rbm.endpointsUpdated,
			UpdateFunc: controller.PassNew(rbm.endpointsUpdated),
			DeleteFunc: rbm.endpointsDeleted,
		},
	})

	return rbm
}

func NewRevisionBackendsManager(updateCh chan<- *RevisionDestsUpdate,
	transport http.RoundTripper, revisionLister servinglisters.RevisionLister,
	serviceLister corev1listers.ServiceLister, endpointsInformer corev1informers.EndpointsInformer,
	logger *zap.SugaredLogger) *RevisionBackendsManager {
	return NewRevisionBackendsManagerWithProbeFrequency(updateCh, transport, revisionLister, serviceLister,
		endpointsInformer, logger, probeFrequency)
}

func (rbm *RevisionBackendsManager) getRevisionProtocol(revID types.NamespacedName) (networking.ProtocolType, error) {
	revision, err := rbm.revisionLister.Revisions(revID.Namespace).Get(revID.Name)
	if err != nil {
		return "", err
	}
	return revision.GetProtocol(), nil
}

func (rbm *RevisionBackendsManager) getOrCreateDestsCh(rev types.NamespacedName) (chan []string, error) {
	rbm.revisionWatchersMux.Lock()
	defer rbm.revisionWatchersMux.Unlock()

	rwCh, ok := rbm.revisionWatchers[rev]
	if !ok {
		proto, err := rbm.getRevisionProtocol(rev)
		if err != nil {
			return nil, err
		}

		destsCh := make(chan []string)
		rw := newRevisionWatcher(rev, proto, rbm.updateCh, destsCh, rbm.transport, rbm.serviceLister, rbm.logger)
		rbm.revisionWatchers[rev] = &revisionWatcherCh{rw, destsCh}
		go rw.run(rbm.probeFrequency)
		return destsCh, nil
	}

	return rwCh.ch, nil
}

// endpointsUpdated is a handler function to be used by the Endpoints informer.
// It updates the endpoints in the RevisionBackendsManager if the hosts changed
func (rbm *RevisionBackendsManager) endpointsUpdated(newObj interface{}) {
	rbm.logger.Debugf("Updating Endpoints: %+v", newObj)
	endpoints := newObj.(*corev1.Endpoints)
	revID := types.NamespacedName{endpoints.Namespace, endpoints.Labels[serving.RevisionLabelKey]}

	destsCh, err := rbm.getOrCreateDestsCh(revID)
	if err != nil {
		rbm.logger.Errorw(fmt.Sprintf("Failed to get revision watcher for revision %q", revID.String()),
			zap.Error(err))
		return
	}
	destsCh <- EndpointsToDests(endpoints)
}

// deleteRevisionWatcher deletes the revision wathcher for rev if it exists. It expects
// a write lock is held on revisionWatchersMux when calling.
func (rbm *RevisionBackendsManager) deleteRevisionWatcher(rev types.NamespacedName) {
	if rw, ok := rbm.revisionWatchers[rev]; ok {
		close(rw.ch)
		delete(rbm.revisionWatchers, rev)
	}
}

func (rbm *RevisionBackendsManager) endpointsDeleted(obj interface{}) {
	ep := obj.(*corev1.Endpoints)
	revID := types.NamespacedName{ep.Namespace, ep.Labels[serving.RevisionLabelKey]}

	rbm.revisionWatchersMux.Lock()
	defer rbm.revisionWatchersMux.Unlock()
	rbm.deleteRevisionWatcher(revID)
}

// Clear removes all watches and essentially "shuts down" the PodIPWatcher. This should
// be called after endpointsInformer is shut down as any subsequent informer events will
// cause new watchers to be created.
func (rbm *RevisionBackendsManager) Clear() {
	rbm.revisionWatchersMux.Lock()
	defer rbm.revisionWatchersMux.Unlock()

	for rev := range rbm.revisionWatchers {
		rbm.deleteRevisionWatcher(rev)
	}
}
<commit_msg>Remove useless make(map) in revisionbackends (#5051)<commit_after>/*
Copyright 2019 The Knative Authors

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

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

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

package activator

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"reflect"
	"strconv"
	"sync"
	"time"

	"go.uber.org/zap"
	"golang.org/x/sync/errgroup"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/types"
	corev1informers "k8s.io/client-go/informers/core/v1"
	corev1listers "k8s.io/client-go/listers/core/v1"
	"k8s.io/client-go/tools/cache"
	"knative.dev/pkg/controller"
	"knative.dev/serving/pkg/apis/networking"
	"knative.dev/serving/pkg/apis/serving"
	servinglisters "knative.dev/serving/pkg/client/listers/serving/v1alpha1"
	"knative.dev/serving/pkg/network"
	"knative.dev/serving/pkg/network/prober"
	"knative.dev/serving/pkg/queue"
	"knative.dev/serving/pkg/reconciler"
)

// RevisionDestsUpdate contains the state of healthy l4 dests for talking to a revision and is the
// primary output from the RevisionBackendsManager system. If a healthy ClusterIP is found then
// ClusterIPDest will be set to non empty string and Dests will be nil. Otherwise Dests will be set
// to a slice of healthy l4 dests for reaching the revision.
type RevisionDestsUpdate struct {
	Rev           types.NamespacedName
	ClusterIPDest string
	Dests         []string
}

const (
	probePortName  string        = "http"
	probeTimeout   time.Duration = 300 * time.Millisecond
	probeFrequency time.Duration = 200 * time.Millisecond
)

// revisionWatcher watches the podIPs and ClusterIP of the service for a revision. It implements the logic
// to supply RevisionDestsUpdate events on updateCh
type revisionWatcher struct {
	rev      types.NamespacedName
	protocol networking.ProtocolType
	updateCh chan<- *RevisionDestsUpdate

	// Stores the state of dests (podIPs) we know about
	healthStates map[string]bool
	// Stores whether the service ClusterIP has been seen as healthy
	clusterIPHealthy bool

	transport     http.RoundTripper
	destsChan     <-chan []string
	serviceLister corev1listers.ServiceLister
	logger        *zap.SugaredLogger
}

func newRevisionWatcher(rev types.NamespacedName, protocol networking.ProtocolType,
	updateCh chan<- *RevisionDestsUpdate, destsChan <-chan []string,
	transport http.RoundTripper, serviceLister corev1listers.ServiceLister,
	logger *zap.SugaredLogger) *revisionWatcher {
	return &revisionWatcher{
		rev:           rev,
		protocol:      protocol,
		updateCh:      updateCh,
		healthStates:  make(map[string]bool),
		transport:     transport,
		destsChan:     destsChan,
		serviceLister: serviceLister,
		logger:        logger,
	}
}

func filterHealthyDests(dests map[string]bool) []string {
	ret := make([]string, 0, len(dests))
	for dest, healthy := range dests {
		if healthy {
			ret = append(ret, dest)
		}
	}
	return ret
}

type destHealth struct {
	dest   string
	health bool
}

func (rw *revisionWatcher) getK8sPrivateService() (*corev1.Service, error) {
	selector := labels.SelectorFromSet(map[string]string{
		serving.RevisionLabelKey:  rw.rev.Name,
		networking.ServiceTypeKey: string(networking.ServiceTypePrivate),
	})
	svcList, err := rw.serviceLister.Services(rw.rev.Namespace).List(selector)
	if err != nil {
		return nil, err
	}

	switch len(svcList) {
	case 0:
		return nil, fmt.Errorf("found no private services for revision %q", rw.rev.String())
	case 1:
		return svcList[0], nil
	default:
		return nil, fmt.Errorf("found multiple private services matching revision %v", rw.rev)
	}
}

func (rw *revisionWatcher) probe(ctx context.Context, dest string) (bool, error) {
	httpDest := url.URL{
		Scheme: "http",
		Host:   dest,
	}
	return prober.Do(ctx, rw.transport, httpDest.String(),
		prober.WithHeader(network.ProbeHeaderName, queue.Name),
		prober.ExpectsBody(queue.Name))

}

func (rw *revisionWatcher) probeClusterIP(svc *corev1.Service) (bool, string, error) {
	if svc.Spec.ClusterIP == "" {
		return false, "", fmt.Errorf("private service %s/%s clusterIP is nil, this should never happen", svc.ObjectMeta.Namespace, svc.ObjectMeta.Name)
	}

	svcPort, ok := GetServicePort(rw.protocol, svc)
	if !ok {
		return false, "", fmt.Errorf("unable to find port in service %s/%s", svc.Namespace, svc.Name)
	}

	// Context used for our probe requests
	ctx, cancel := context.WithTimeout(context.Background(), probeTimeout)
	defer cancel()

	dest := net.JoinHostPort(svc.Spec.ClusterIP, strconv.Itoa(svcPort))
	ok, err := rw.probe(ctx, dest)
	return ok, dest, err
}

func (rw *revisionWatcher) probePodIPs(dests []string) (map[string]bool, error) {
	// Context used for our probe requests
	ctx, cancel := context.WithTimeout(context.Background(), probeTimeout)
	defer cancel()

	var probeGroup errgroup.Group
	healthStatesCh := make(chan destHealth, len(dests))

	for _, dest := range dests {
		// If the dest is already healthy then preserve that.
		if curHealthy, ok := rw.healthStates[dest]; ok && curHealthy {
			healthStatesCh <- destHealth{dest, true}
			continue
		}

		pDest := dest
		probeGroup.Go(func() error {
			ok, err := rw.probe(ctx, pDest)
			healthStatesCh <- destHealth{pDest, ok}
			return err
		})
	}

	err := probeGroup.Wait()
	close(healthStatesCh)

	healthStates := make(map[string]bool, len(dests))
	for dh := range healthStatesCh {
		healthStates[dh.dest] = dh.health
	}

	return healthStates, err
}

// checkDests performs probing and potentially sends a dests update. It is
// assumed this method is not called concurrently.
func (rw *revisionWatcher) checkDests(dests []string) {
	if len(dests) == 0 {
		if rw.clusterIPHealthy {
			// we have a healthy clusterIP but revision is not ready. We must have scaled down.
			rw.clusterIPHealthy = false

			// Send update that were now inactive
			rw.updateCh <- &RevisionDestsUpdate{Rev: rw.rev}
		}

		// We know this revision cannot be healthy so short circuit
		return
	}

	if rw.clusterIPHealthy {
		// cluster IP is healthy and we havent scaled down, short circuit
		return
	}

	// First check the clusterIP
	svc, err := rw.getK8sPrivateService()
	if err != nil {
		rw.logger.Errorw("Failed to lookup private service for revision", zap.Error(err))
		return
	}

	// If clusterIP is healthy send this update and we are done
	if ok, dest, err := rw.probeClusterIP(svc); err != nil {
		rw.logger.Errorw(fmt.Sprintf("Failed to probe clusterIP %s/%s", svc.Namespace, svc.Name), zap.Error(err))
	} else if ok {
		rw.clusterIPHealthy = true
		rw.healthStates = nil
		rw.updateCh <- &RevisionDestsUpdate{Rev: rw.rev, ClusterIPDest: dest}
		return
	}

	healthStates, err := rw.probePodIPs(dests)
	if err != nil {
		rw.logger.Errorw("Failed probing", zap.Error(err))
		// We dont want to return here as an error still affects health states
	}

	rw.logger.Debugf("Done probing, got healthStates %v", healthStates)
	if !reflect.DeepEqual(rw.healthStates, healthStates) {
		rw.healthStates = healthStates
		destsArr := filterHealthyDests(healthStates)
		rw.updateCh <- &RevisionDestsUpdate{
			Rev:   rw.rev,
			Dests: destsArr,
		}
	}
}

func (rw *revisionWatcher) runWithTickCh(tickCh <-chan time.Time) {
	var dests []string
	for {
		select {
		case x, ok := <-rw.destsChan:
			if !ok {
				// shutdown
				return
			}
			dests = x
		case <-tickCh:
		}
		rw.checkDests(dests)
	}
}

func (rw *revisionWatcher) run(probeFrequency time.Duration) {
	ticker := time.NewTicker(probeFrequency)
	defer ticker.Stop()

	rw.runWithTickCh(ticker.C)
}

type revisionWatcherCh struct {
	revisionWatcher *revisionWatcher
	ch              chan []string
}

// RevisionBackendsManager listens to revision endpoints and keeps track of healthy
// l4 dests which can be used to reach a revision
type RevisionBackendsManager struct {
	revisionLister servinglisters.RevisionLister
	serviceLister  corev1listers.ServiceLister

	revisionWatchers    map[types.NamespacedName]*revisionWatcherCh
	revisionWatchersMux sync.RWMutex

	updateCh       chan<- *RevisionDestsUpdate
	transport      http.RoundTripper
	logger         *zap.SugaredLogger
	probeFrequency time.Duration
}

// NewRevisionBackendsManagerWithProbeFrequency returnes a RevisionBackendsManager that uses the supplied
// probe frequency
func NewRevisionBackendsManagerWithProbeFrequency(updateCh chan<- *RevisionDestsUpdate,
	transport http.RoundTripper, revisionLister servinglisters.RevisionLister,
	serviceLister corev1listers.ServiceLister, endpointsInformer corev1informers.EndpointsInformer,
	logger *zap.SugaredLogger, probeFrequency time.Duration) *RevisionBackendsManager {
	rbm := &RevisionBackendsManager{
		revisionLister:   revisionLister,
		serviceLister:    serviceLister,
		revisionWatchers: make(map[types.NamespacedName]*revisionWatcherCh),
		updateCh:         updateCh,
		transport:        transport,
		logger:           logger,
		probeFrequency:   probeFrequency,
	}

	endpointsInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
		FilterFunc: reconciler.ChainFilterFuncs(
			reconciler.LabelExistsFilterFunc(serving.RevisionUID),
			// We are only interested in the private services, since that is
			// what is populated by the actual revision backends.
			reconciler.LabelFilterFunc(networking.ServiceTypeKey, string(networking.ServiceTypePrivate), false),
		),
		Handler: cache.ResourceEventHandlerFuncs{
			AddFunc:    rbm.endpointsUpdated,
			UpdateFunc: controller.PassNew(rbm.endpointsUpdated),
			DeleteFunc: rbm.endpointsDeleted,
		},
	})

	return rbm
}

func NewRevisionBackendsManager(updateCh chan<- *RevisionDestsUpdate,
	transport http.RoundTripper, revisionLister servinglisters.RevisionLister,
	serviceLister corev1listers.ServiceLister, endpointsInformer corev1informers.EndpointsInformer,
	logger *zap.SugaredLogger) *RevisionBackendsManager {
	return NewRevisionBackendsManagerWithProbeFrequency(updateCh, transport, revisionLister, serviceLister,
		endpointsInformer, logger, probeFrequency)
}

func (rbm *RevisionBackendsManager) getRevisionProtocol(revID types.NamespacedName) (networking.ProtocolType, error) {
	revision, err := rbm.revisionLister.Revisions(revID.Namespace).Get(revID.Name)
	if err != nil {
		return "", err
	}
	return revision.GetProtocol(), nil
}

func (rbm *RevisionBackendsManager) getOrCreateDestsCh(rev types.NamespacedName) (chan []string, error) {
	rbm.revisionWatchersMux.Lock()
	defer rbm.revisionWatchersMux.Unlock()

	rwCh, ok := rbm.revisionWatchers[rev]
	if !ok {
		proto, err := rbm.getRevisionProtocol(rev)
		if err != nil {
			return nil, err
		}

		destsCh := make(chan []string)
		rw := newRevisionWatcher(rev, proto, rbm.updateCh, destsCh, rbm.transport, rbm.serviceLister, rbm.logger)
		rbm.revisionWatchers[rev] = &revisionWatcherCh{rw, destsCh}
		go rw.run(rbm.probeFrequency)
		return destsCh, nil
	}

	return rwCh.ch, nil
}

// endpointsUpdated is a handler function to be used by the Endpoints informer.
// It updates the endpoints in the RevisionBackendsManager if the hosts changed
func (rbm *RevisionBackendsManager) endpointsUpdated(newObj interface{}) {
	rbm.logger.Debugf("Updating Endpoints: %+v", newObj)
	endpoints := newObj.(*corev1.Endpoints)
	revID := types.NamespacedName{endpoints.Namespace, endpoints.Labels[serving.RevisionLabelKey]}

	destsCh, err := rbm.getOrCreateDestsCh(revID)
	if err != nil {
		rbm.logger.Errorw(fmt.Sprintf("Failed to get revision watcher for revision %q", revID.String()),
			zap.Error(err))
		return
	}
	destsCh <- EndpointsToDests(endpoints)
}

// deleteRevisionWatcher deletes the revision wathcher for rev if it exists. It expects
// a write lock is held on revisionWatchersMux when calling.
func (rbm *RevisionBackendsManager) deleteRevisionWatcher(rev types.NamespacedName) {
	if rw, ok := rbm.revisionWatchers[rev]; ok {
		close(rw.ch)
		delete(rbm.revisionWatchers, rev)
	}
}

func (rbm *RevisionBackendsManager) endpointsDeleted(obj interface{}) {
	ep := obj.(*corev1.Endpoints)
	revID := types.NamespacedName{ep.Namespace, ep.Labels[serving.RevisionLabelKey]}

	rbm.revisionWatchersMux.Lock()
	defer rbm.revisionWatchersMux.Unlock()
	rbm.deleteRevisionWatcher(revID)
}

// Clear removes all watches and essentially "shuts down" the PodIPWatcher. This should
// be called after endpointsInformer is shut down as any subsequent informer events will
// cause new watchers to be created.
func (rbm *RevisionBackendsManager) Clear() {
	rbm.revisionWatchersMux.Lock()
	defer rbm.revisionWatchersMux.Unlock()

	for rev := range rbm.revisionWatchers {
		rbm.deleteRevisionWatcher(rev)
	}
}
<|endoftext|>


<commit_before>// Package httpclient is a lightweight implementation of a client for the HTTP gateway.
package httpclient

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/golang/protobuf/jsonpb"
	"github.com/golang/protobuf/proto"
	"github.com/opentracing/opentracing-go"
	"github.com/sirupsen/logrus"
)

var (
	ErrResponseError = errors.New("response error")
	ErrRequestCreate = errors.New("failed to create request")
	ErrRequestSend   = errors.New("failed to send request")
	ErrSerialize     = errors.New("failed to serialize input")
	ErrDeserialize   = errors.New("failed to deserialize input")
)

var defaultHTTPClient = http.Client{}
var defaultJSONPBMarshaller = jsonpb.Marshaler{}

func toJSON(dst io.Writer, m proto.Message) error {
	return defaultJSONPBMarshaller.Marshal(dst, m)
}

func fromJSON(src io.Reader, dst proto.Message) error {
	return jsonpb.Unmarshal(src, dst)
}

func callWithJSON(ctx context.Context, method string, url string, in proto.Message, out proto.Message) error {
	buf := bytes.NewBuffer(nil)
	if in != nil {
		err := toJSON(buf, in)
		if err != nil {
			return fmt.Errorf("%v: %v", ErrSerialize, err)
		}
	}
	if logrus.GetLevel() == logrus.DebugLevel {
		logrus.Debugf("--> %s %s", method, url)
		if in != nil {
			buf := bytes.NewBuffer(nil)
			err := toJSON(buf, in)
			if err != nil {
				logrus.Errorf("Failed to jsonify debug data: %v", err)
			}
			data, err := ioutil.ReadAll(buf)
			if err != nil {
				logrus.Errorf("Failed to read debug data: %v", err)
			}
			logrus.Debugf("body: '%v'", data)
		}
	}
	req, err := http.NewRequest(method, url, buf)
	if err != nil {
		return fmt.Errorf("%v: %v", ErrRequestCreate, err)
	}
	req.Header.Set("Content-Type", "application/json")

	// If set, inject opentracing into HTTP request
	span := opentracing.SpanFromContext(ctx)
	if span != nil {
		carrier := opentracing.HTTPHeadersCarrier(req.Header)
		opentracing.GlobalTracer().Inject(span.Context(), opentracing.HTTPHeaders, carrier)
	}

	resp, err := defaultHTTPClient.Do(req.WithContext(ctx))
	if err != nil {
		return fmt.Errorf("%v: %v", ErrRequestSend, err)
	}
	if logrus.GetLevel() == logrus.DebugLevel {
		logrus.Debugf("<-- %s - %s", resp.Status, url)
		if resp.Body != nil {
			data, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				logrus.Errorf("Failed to read debug body: %v", err)
			}
			logrus.Debugf("Body: '%v'", string(data))
		}
	}
	if resp.StatusCode >= 400 {
		data, _ := ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		return fmt.Errorf("%v (%s): %s", ErrResponseError, resp.Status, strings.TrimSpace(string(data)))
	}

	if out != nil && resp.ContentLength != 0 {

		err = fromJSON(resp.Body, out)
		if err != nil {
			return fmt.Errorf("%v: %v", ErrDeserialize, err)
		}
		resp.Body.Close()
		if err != nil {
			logrus.Errorf("Failed to close response body: %v", err)
		}
	}
	return nil
}

type baseAPI struct {
	endpoint string
	client   http.Client
}

func (api *baseAPI) formatURL(path string) string {
	return api.endpoint + path
}
<commit_msg>httpclient: fixed debug part exhausting the body reader<commit_after>// Package httpclient is a lightweight implementation of a client for the HTTP gateway.
package httpclient

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/golang/protobuf/jsonpb"
	"github.com/golang/protobuf/proto"
	"github.com/opentracing/opentracing-go"
	"github.com/sirupsen/logrus"
)

var (
	ErrResponseError = errors.New("response error")
	ErrRequestCreate = errors.New("failed to create request")
	ErrRequestSend   = errors.New("failed to send request")
	ErrSerialize     = errors.New("failed to serialize input")
	ErrDeserialize   = errors.New("failed to deserialize input")
)

var defaultHTTPClient = http.Client{}
var defaultJSONPBMarshaller = jsonpb.Marshaler{}

func toJSON(dst io.Writer, m proto.Message) error {
	return defaultJSONPBMarshaller.Marshal(dst, m)
}

func fromJSON(src io.Reader, dst proto.Message) error {
	return jsonpb.Unmarshal(src, dst)
}

func callWithJSON(ctx context.Context, method string, url string, in proto.Message, out proto.Message) error {
	buf := bytes.NewBuffer(nil)
	if in != nil {
		err := toJSON(buf, in)
		if err != nil {
			return fmt.Errorf("%v: %v", ErrSerialize, err)
		}
	}
	if logrus.GetLevel() == logrus.DebugLevel {
		logrus.Debugf("--> %s %s", method, url)
		if in != nil {
			buf := bytes.NewBuffer(nil)
			err := toJSON(buf, in)
			if err != nil {
				logrus.Errorf("Failed to jsonify debug data: %v", err)
			}
			data, err := ioutil.ReadAll(buf)
			if err != nil {
				logrus.Errorf("Failed to read debug data: %v", err)
			}
			logrus.Debugf("Request body: '%v'", string(data))
		}
	}
	req, err := http.NewRequest(method, url, buf)
	if err != nil {
		return fmt.Errorf("%v: %v", ErrRequestCreate, err)
	}
	req.Header.Set("Content-Type", "application/json")

	// If set, inject opentracing into HTTP request
	span := opentracing.SpanFromContext(ctx)
	if span != nil {
		carrier := opentracing.HTTPHeadersCarrier(req.Header)
		opentracing.GlobalTracer().Inject(span.Context(), opentracing.HTTPHeaders, carrier)
	}

	resp, err := defaultHTTPClient.Do(req.WithContext(ctx))
	if err != nil {
		return fmt.Errorf("%v: %v", ErrRequestSend, err)
	}
	var respBody []byte
	logrus.Debugf("<-- %s - %s", resp.Status, url)
	if resp.Body != nil {
		respBody, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			logrus.Errorf("Failed to read debug body: %v", err)
		}
		logrus.Debugf("Response body: '%v'", string(respBody))
	}
	resp.Body.Close()

	// Handle error responses
	if resp.StatusCode >= 400 {
		return fmt.Errorf("%v (%s): %s", ErrResponseError, resp.Status, strings.TrimSpace(string(respBody)))
	}

	if out != nil && resp.ContentLength != 0 {
		err = fromJSON(bytes.NewReader(respBody), out)
		if err != nil {
			return fmt.Errorf("%v: %v", ErrDeserialize, err)
		}
		if err != nil {
			logrus.Errorf("Failed to close response body: %v", err)
		}
	}
	return nil
}

type baseAPI struct {
	endpoint string
	client   http.Client
}

func (api *baseAPI) formatURL(path string) string {
	return api.endpoint + path
}
<|endoftext|>


<commit_before>/*
Copyright 2020 The cert-manager 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 rfc2136 implements a DNS provider for solving the DNS-01 challenge
// using the rfc2136 dynamic update.
// This code was adapted from lego:
// 	  https://github.com/xenolf/lego

package rfc2136

import (
	"fmt"
	"strings"
	"time"

	logf "github.com/jetstack/cert-manager/pkg/logs"

	"github.com/miekg/dns"

	"github.com/jetstack/cert-manager/pkg/internal/apis/certmanager/validation/util"
)

var defaultPort = "53"

// This list must be kept in sync with pkg/apis/certmanager/validation/issuer.go
var supportedAlgorithms = map[string]string{
	"HMACMD5":    dns.HmacMD5,
	"HMACSHA1":   dns.HmacSHA1,
	"HMACSHA256": dns.HmacSHA256,
	"HMACSHA512": dns.HmacSHA512,
}

// DNSProvider is an implementation of the acme.ChallengeProvider interface that
// uses dynamic DNS updates (RFC 2136) to create TXT records on a nameserver.
type DNSProvider struct {
	nameserver    string
	tsigAlgorithm string
	tsigKeyName   string
	tsigSecret    string
}

// NewDNSProviderCredentials uses the supplied credentials to return a
// DNSProvider instance configured for rfc2136 dynamic update. To disable TSIG
// authentication, leave the TSIG parameters as empty strings.
// nameserver must be a network address in the form "IP" or "IP:port".
func NewDNSProviderCredentials(nameserver, tsigAlgorithm, tsigKeyName, tsigSecret string) (*DNSProvider, error) {
	logf.Log.V(logf.DebugLevel).Info("Creating RFC2136 Provider")

	d := &DNSProvider{}

	if validNameserver, err := util.ValidNameserver(nameserver); err != nil {
		return nil, err
	} else {
		d.nameserver = validNameserver
	}

	if len(tsigKeyName) > 0 && len(tsigSecret) > 0 {
		d.tsigKeyName = tsigKeyName
		d.tsigSecret = tsigSecret
	}

	if tsigAlgorithm == "" {
		tsigAlgorithm = dns.HmacMD5
	} else {
		if value, ok := supportedAlgorithms[strings.ToUpper(tsigAlgorithm)]; ok {
			tsigAlgorithm = value
		} else {
			return nil, fmt.Errorf("the algorithm '%v' is not supported", tsigAlgorithm)

		}
	}
	d.tsigAlgorithm = tsigAlgorithm

	logf.V(logf.DebugLevel).Infof("DNSProvider nameserver:       %s\n", d.nameserver)
	logf.V(logf.DebugLevel).Infof("            tsigAlgorithm:    %s\n", d.tsigAlgorithm)
	logf.V(logf.DebugLevel).Infof("            tsigKeyName:      %s\n", d.tsigKeyName)
	keyLen := len(d.tsigSecret)
	mask := make([]rune, keyLen/2)
	for i := range mask {
		mask[i] = '*'
	}
	masked := d.tsigSecret[0:keyLen/4] + string(mask) + d.tsigSecret[keyLen/4*3:keyLen]
	logf.V(logf.DebugLevel).Infof("            tsigSecret:       %s\n", masked)

	return d, nil
}

// Present creates a TXT record using the specified parameters
func (r *DNSProvider) Present(_, fqdn, zone, value string) error {
	return r.changeRecord("INSERT", fqdn, zone, value, 60)
}

// CleanUp removes the TXT record matching the specified parameters
func (r *DNSProvider) CleanUp(_, fqdn, zone, value string) error {
	return r.changeRecord("REMOVE", fqdn, zone, value, 60)
}

func (r *DNSProvider) changeRecord(action, fqdn, zone, value string, ttl int) error {
	// Create RR
	rr := new(dns.TXT)
	rr.Hdr = dns.RR_Header{Name: fqdn, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: uint32(ttl)}
	rr.Txt = []string{value}
	rrs := []dns.RR{rr}

	// Create dynamic update packet
	m := new(dns.Msg)
	m.SetUpdate(zone)
	switch action {
	case "INSERT":
		m.Insert(rrs)
	case "REMOVE":
		m.Remove(rrs)
	default:
		return fmt.Errorf("unexpected action: %s", action)
	}

	// Setup client
	c := new(dns.Client)
	c.SingleInflight = true
	// TSIG authentication / msg signing
	if len(r.tsigKeyName) > 0 && len(r.tsigSecret) > 0 {
		m.SetTsig(dns.Fqdn(r.tsigKeyName), r.tsigAlgorithm, 300, time.Now().Unix())
		c.TsigSecret = map[string]string{dns.Fqdn(r.tsigKeyName): r.tsigSecret}
	}

	// Send the query
	reply, _, err := c.Exchange(m, r.nameserver)
	if err != nil {
		return fmt.Errorf("DNS update failed: %v", err)
	}
	if reply != nil && reply.Rcode != dns.RcodeSuccess {
		return fmt.Errorf("DNS update failed. Server replied: %s", dns.RcodeToString[reply.Rcode])
	}

	return nil
}
<commit_msg>rfc2136 dns01: "the algothrim" -> "algorithm is not supported"<commit_after>/*
Copyright 2020 The cert-manager 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 rfc2136 implements a DNS provider for solving the DNS-01 challenge
// using the rfc2136 dynamic update.
// This code was adapted from lego:
// 	  https://github.com/xenolf/lego

package rfc2136

import (
	"fmt"
	"strings"
	"time"

	logf "github.com/jetstack/cert-manager/pkg/logs"

	"github.com/miekg/dns"

	"github.com/jetstack/cert-manager/pkg/internal/apis/certmanager/validation/util"
)

var defaultPort = "53"

// This list must be kept in sync with pkg/apis/certmanager/validation/issuer.go
var supportedAlgorithms = map[string]string{
	"HMACMD5":    dns.HmacMD5,
	"HMACSHA1":   dns.HmacSHA1,
	"HMACSHA256": dns.HmacSHA256,
	"HMACSHA512": dns.HmacSHA512,
}

// DNSProvider is an implementation of the acme.ChallengeProvider interface that
// uses dynamic DNS updates (RFC 2136) to create TXT records on a nameserver.
type DNSProvider struct {
	nameserver    string
	tsigAlgorithm string
	tsigKeyName   string
	tsigSecret    string
}

// NewDNSProviderCredentials uses the supplied credentials to return a
// DNSProvider instance configured for rfc2136 dynamic update. To disable TSIG
// authentication, leave the TSIG parameters as empty strings.
// nameserver must be a network address in the form "IP" or "IP:port".
func NewDNSProviderCredentials(nameserver, tsigAlgorithm, tsigKeyName, tsigSecret string) (*DNSProvider, error) {
	logf.Log.V(logf.DebugLevel).Info("Creating RFC2136 Provider")

	d := &DNSProvider{}

	if validNameserver, err := util.ValidNameserver(nameserver); err != nil {
		return nil, err
	} else {
		d.nameserver = validNameserver
	}

	if len(tsigKeyName) > 0 && len(tsigSecret) > 0 {
		d.tsigKeyName = tsigKeyName
		d.tsigSecret = tsigSecret
	}

	if tsigAlgorithm == "" {
		tsigAlgorithm = dns.HmacMD5
	} else {
		if value, ok := supportedAlgorithms[strings.ToUpper(tsigAlgorithm)]; ok {
			tsigAlgorithm = value
		} else {
			return nil, fmt.Errorf("algorithm '%v' is not supported", tsigAlgorithm)

		}
	}
	d.tsigAlgorithm = tsigAlgorithm

	logf.V(logf.DebugLevel).Infof("DNSProvider nameserver:       %s\n", d.nameserver)
	logf.V(logf.DebugLevel).Infof("            tsigAlgorithm:    %s\n", d.tsigAlgorithm)
	logf.V(logf.DebugLevel).Infof("            tsigKeyName:      %s\n", d.tsigKeyName)
	keyLen := len(d.tsigSecret)
	mask := make([]rune, keyLen/2)
	for i := range mask {
		mask[i] = '*'
	}
	masked := d.tsigSecret[0:keyLen/4] + string(mask) + d.tsigSecret[keyLen/4*3:keyLen]
	logf.V(logf.DebugLevel).Infof("            tsigSecret:       %s\n", masked)

	return d, nil
}

// Present creates a TXT record using the specified parameters
func (r *DNSProvider) Present(_, fqdn, zone, value string) error {
	return r.changeRecord("INSERT", fqdn, zone, value, 60)
}

// CleanUp removes the TXT record matching the specified parameters
func (r *DNSProvider) CleanUp(_, fqdn, zone, value string) error {
	return r.changeRecord("REMOVE", fqdn, zone, value, 60)
}

func (r *DNSProvider) changeRecord(action, fqdn, zone, value string, ttl int) error {
	// Create RR
	rr := new(dns.TXT)
	rr.Hdr = dns.RR_Header{Name: fqdn, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: uint32(ttl)}
	rr.Txt = []string{value}
	rrs := []dns.RR{rr}

	// Create dynamic update packet
	m := new(dns.Msg)
	m.SetUpdate(zone)
	switch action {
	case "INSERT":
		m.Insert(rrs)
	case "REMOVE":
		m.Remove(rrs)
	default:
		return fmt.Errorf("unexpected action: %s", action)
	}

	// Setup client
	c := new(dns.Client)
	c.SingleInflight = true
	// TSIG authentication / msg signing
	if len(r.tsigKeyName) > 0 && len(r.tsigSecret) > 0 {
		m.SetTsig(dns.Fqdn(r.tsigKeyName), r.tsigAlgorithm, 300, time.Now().Unix())
		c.TsigSecret = map[string]string{dns.Fqdn(r.tsigKeyName): r.tsigSecret}
	}

	// Send the query
	reply, _, err := c.Exchange(m, r.nameserver)
	if err != nil {
		return fmt.Errorf("DNS update failed: %v", err)
	}
	if reply != nil && reply.Rcode != dns.RcodeSuccess {
		return fmt.Errorf("DNS update failed. Server replied: %s", dns.RcodeToString[reply.Rcode])
	}

	return nil
}
<|endoftext|>


<commit_before>/*
Copyright 2016 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 cm

import (
	"fmt"
	"path"

	libcontainercgroups "github.com/opencontainers/runc/libcontainer/cgroups"
	cgroupfs "github.com/opencontainers/runc/libcontainer/cgroups/fs"
	libcontainerconfigs "github.com/opencontainers/runc/libcontainer/configs"
)

// cgroupManagerImpl implements the CgroupManager interface.
// Its a stateless object which can be used to
// update,create or delete any number of cgroups
// It uses the Libcontainer raw fs cgroup manager for cgroup management.
type cgroupManagerImpl struct {
	// subsystems holds information about all the
	// mounted cgroup subsytems on the node
	subsystems *cgroupSubsystems
}

// Make sure that cgroupManagerImpl implements the CgroupManager interface
var _ CgroupManager = &cgroupManagerImpl{}

// NewCgroupManager is a factory method that returns a CgroupManager
func NewCgroupManager(cs *cgroupSubsystems) CgroupManager {
	return &cgroupManagerImpl{
		subsystems: cs,
	}
}

// Exists checks if all subsystem cgroups already exist
func (m *cgroupManagerImpl) Exists(name string) bool {
	// Get map of all cgroup paths on the system for the particular cgroup
	cgroupPaths := make(map[string]string, len(m.subsystems.mountPoints))
	for key, val := range m.subsystems.mountPoints {
		cgroupPaths[key] = path.Join(val, name)
	}

	// If even one cgroup doesn't exist we go on to create it
	// @TODO(dubstack) We skip check for systemd until we update
	// libcontainer in vendor
	for key, path := range cgroupPaths {
		if key != "systemd" && !libcontainercgroups.PathExists(path) {
			return false
		}
	}
	return true
}

// Destroy destroys the specified cgroup
func (m *cgroupManagerImpl) Destroy(cgroupConfig *CgroupConfig) error {
	//cgroup name
	name := cgroupConfig.Name

	// Get map of all cgroup paths on the system for the particular cgroup
	cgroupPaths := make(map[string]string, len(m.subsystems.mountPoints))
	for key, val := range m.subsystems.mountPoints {
		cgroupPaths[key] = path.Join(val, name)
	}

	// Initialize libcontainer's cgroup config
	libcontainerCgroupConfig := &libcontainerconfigs.Cgroup{
		Name:   path.Base(name),
		Parent: path.Dir(name),
	}
	fsCgroupManager := cgroupfs.Manager{
		Cgroups: libcontainerCgroupConfig,
		Paths:   cgroupPaths,
	}

	// Delete cgroups using libcontainers Managers Destroy() method
	if err := fsCgroupManager.Destroy(); err != nil {
		return fmt.Errorf("Unable to destroy cgroup paths for cgroup %v : %v", name, err)
	}
	return nil
}

type subsystem interface {
	// Name returns the name of the subsystem.
	Name() string
	// Set the cgroup represented by cgroup.
	Set(path string, cgroup *libcontainerconfigs.Cgroup) error
}

// Cgroup subsystems we currently support
var supportedSubsystems []subsystem = []subsystem{
	&cgroupfs.MemoryGroup{},
	&cgroupfs.CpuGroup{},
}

// setSupportedSubsytems sets cgroup resource limits only on the supported
// subsytems. ie. cpu and memory. We don't use libcontainer's cgroup/fs/Set()
// method as it dosn't allow us to skip updates on the devices cgroup
// Allowing or denying all devices by writing 'a' to devices.allow or devices.deny is
// not possible once the device cgroups has children. Once the pod level cgroup are
// created under the QOS level cgroup we cannot update the QOS level device cgroup.
// We would like to skip setting any values on the device cgroup in this case
// but this is not possible with libcontainers Set() method
// See https://github.com/opencontainers/runc/issues/932
func setSupportedSubsytems(cgroupConfig *libcontainerconfigs.Cgroup) error {
	for _, sys := range supportedSubsystems {
		if _, ok := cgroupConfig.Paths[sys.Name()]; !ok {
			return fmt.Errorf("Failed to find subsytem mount for subsytem")
		}
		if err := sys.Set(cgroupConfig.Paths[sys.Name()], cgroupConfig); err != nil {
			return fmt.Errorf("Failed to set config for supported subsystems : %v", err)
		}
	}
	return nil
}

// Update updates the cgroup with the specified Cgroup Configuration
func (m *cgroupManagerImpl) Update(cgroupConfig *CgroupConfig) error {
	//cgroup name
	name := cgroupConfig.Name

	// Extract the cgroup resource parameters
	resourceConfig := cgroupConfig.ResourceParameters
	resources := &libcontainerconfigs.Resources{}
	if resourceConfig.Memory != nil {
		resources.Memory = *resourceConfig.Memory
	}
	if resourceConfig.CpuShares != nil {
		resources.CpuShares = *resourceConfig.CpuShares
	}
	if resourceConfig.CpuQuota != nil {
		resources.CpuQuota = *resourceConfig.CpuQuota
	}

	// Initialize libcontainer's cgroup config
	libcontainerCgroupConfig := &libcontainerconfigs.Cgroup{
		Name:      path.Base(name),
		Parent:    path.Dir(name),
		Resources: resources,
	}

	if err := setSupportedSubsytems(libcontainerCgroupConfig); err != nil {
		return fmt.Errorf("Failed to set supported cgroup subsystems for cgroup %v: %v", name, err)
	}
	return nil
}

// Create creates the specified cgroup
func (m *cgroupManagerImpl) Create(cgroupConfig *CgroupConfig) error {
	// get cgroup name
	name := cgroupConfig.Name

	// Initialize libcontainer's cgroup config
	libcontainerCgroupConfig := &libcontainerconfigs.Cgroup{
		Name:      path.Base(name),
		Parent:    path.Dir(name),
		Resources: &libcontainerconfigs.Resources{},
	}

	// get the fscgroup Manager with the specified cgroup configuration
	fsCgroupManager := &cgroupfs.Manager{
		Cgroups: libcontainerCgroupConfig,
	}
	//Apply(0) is a hack to create the cgroup directories for each resource
	// subsystem. The function [cgroups.Manager.apply()] applies cgroup
	// configuration to the process with the specified pid.
	// It creates cgroup files for each subsytems and writes the pid
	// in the tasks file. We use the function to create all the required
	// cgroup files but not attach any "real" pid to the cgroup.
	if err := fsCgroupManager.Apply(0); err != nil {
		return fmt.Errorf("Failed to apply cgroup config for %v: %v", name, err)
	}
	return nil
}
<commit_msg>Do not skip check for cgroup creation in the systemd mount<commit_after>/*
Copyright 2016 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 cm

import (
	"fmt"
	"path"

	libcontainercgroups "github.com/opencontainers/runc/libcontainer/cgroups"
	cgroupfs "github.com/opencontainers/runc/libcontainer/cgroups/fs"
	libcontainerconfigs "github.com/opencontainers/runc/libcontainer/configs"
)

// cgroupManagerImpl implements the CgroupManager interface.
// Its a stateless object which can be used to
// update,create or delete any number of cgroups
// It uses the Libcontainer raw fs cgroup manager for cgroup management.
type cgroupManagerImpl struct {
	// subsystems holds information about all the
	// mounted cgroup subsytems on the node
	subsystems *cgroupSubsystems
}

// Make sure that cgroupManagerImpl implements the CgroupManager interface
var _ CgroupManager = &cgroupManagerImpl{}

// NewCgroupManager is a factory method that returns a CgroupManager
func NewCgroupManager(cs *cgroupSubsystems) CgroupManager {
	return &cgroupManagerImpl{
		subsystems: cs,
	}
}

// Exists checks if all subsystem cgroups already exist
func (m *cgroupManagerImpl) Exists(name string) bool {
	// Get map of all cgroup paths on the system for the particular cgroup
	cgroupPaths := make(map[string]string, len(m.subsystems.mountPoints))
	for key, val := range m.subsystems.mountPoints {
		cgroupPaths[key] = path.Join(val, name)
	}

	// If even one cgroup doesn't exist we go on to create it
	for _, path := range cgroupPaths {
		if !libcontainercgroups.PathExists(path) {
			return false
		}
	}
	return true
}

// Destroy destroys the specified cgroup
func (m *cgroupManagerImpl) Destroy(cgroupConfig *CgroupConfig) error {
	//cgroup name
	name := cgroupConfig.Name

	// Get map of all cgroup paths on the system for the particular cgroup
	cgroupPaths := make(map[string]string, len(m.subsystems.mountPoints))
	for key, val := range m.subsystems.mountPoints {
		cgroupPaths[key] = path.Join(val, name)
	}

	// Initialize libcontainer's cgroup config
	libcontainerCgroupConfig := &libcontainerconfigs.Cgroup{
		Name:   path.Base(name),
		Parent: path.Dir(name),
	}
	fsCgroupManager := cgroupfs.Manager{
		Cgroups: libcontainerCgroupConfig,
		Paths:   cgroupPaths,
	}

	// Delete cgroups using libcontainers Managers Destroy() method
	if err := fsCgroupManager.Destroy(); err != nil {
		return fmt.Errorf("Unable to destroy cgroup paths for cgroup %v : %v", name, err)
	}
	return nil
}

type subsystem interface {
	// Name returns the name of the subsystem.
	Name() string
	// Set the cgroup represented by cgroup.
	Set(path string, cgroup *libcontainerconfigs.Cgroup) error
}

// Cgroup subsystems we currently support
var supportedSubsystems []subsystem = []subsystem{
	&cgroupfs.MemoryGroup{},
	&cgroupfs.CpuGroup{},
}

// setSupportedSubsytems sets cgroup resource limits only on the supported
// subsytems. ie. cpu and memory. We don't use libcontainer's cgroup/fs/Set()
// method as it dosn't allow us to skip updates on the devices cgroup
// Allowing or denying all devices by writing 'a' to devices.allow or devices.deny is
// not possible once the device cgroups has children. Once the pod level cgroup are
// created under the QOS level cgroup we cannot update the QOS level device cgroup.
// We would like to skip setting any values on the device cgroup in this case
// but this is not possible with libcontainers Set() method
// See https://github.com/opencontainers/runc/issues/932
func setSupportedSubsytems(cgroupConfig *libcontainerconfigs.Cgroup) error {
	for _, sys := range supportedSubsystems {
		if _, ok := cgroupConfig.Paths[sys.Name()]; !ok {
			return fmt.Errorf("Failed to find subsytem mount for subsytem")
		}
		if err := sys.Set(cgroupConfig.Paths[sys.Name()], cgroupConfig); err != nil {
			return fmt.Errorf("Failed to set config for supported subsystems : %v", err)
		}
	}
	return nil
}

// Update updates the cgroup with the specified Cgroup Configuration
func (m *cgroupManagerImpl) Update(cgroupConfig *CgroupConfig) error {
	//cgroup name
	name := cgroupConfig.Name

	// Extract the cgroup resource parameters
	resourceConfig := cgroupConfig.ResourceParameters
	resources := &libcontainerconfigs.Resources{}
	if resourceConfig.Memory != nil {
		resources.Memory = *resourceConfig.Memory
	}
	if resourceConfig.CpuShares != nil {
		resources.CpuShares = *resourceConfig.CpuShares
	}
	if resourceConfig.CpuQuota != nil {
		resources.CpuQuota = *resourceConfig.CpuQuota
	}

	// Initialize libcontainer's cgroup config
	libcontainerCgroupConfig := &libcontainerconfigs.Cgroup{
		Name:      path.Base(name),
		Parent:    path.Dir(name),
		Resources: resources,
	}

	if err := setSupportedSubsytems(libcontainerCgroupConfig); err != nil {
		return fmt.Errorf("Failed to set supported cgroup subsystems for cgroup %v: %v", name, err)
	}
	return nil
}

// Create creates the specified cgroup
func (m *cgroupManagerImpl) Create(cgroupConfig *CgroupConfig) error {
	// get cgroup name
	name := cgroupConfig.Name

	// Initialize libcontainer's cgroup config
	libcontainerCgroupConfig := &libcontainerconfigs.Cgroup{
		Name:      path.Base(name),
		Parent:    path.Dir(name),
		Resources: &libcontainerconfigs.Resources{},
	}

	// get the fscgroup Manager with the specified cgroup configuration
	fsCgroupManager := &cgroupfs.Manager{
		Cgroups: libcontainerCgroupConfig,
	}
	//Apply(0) is a hack to create the cgroup directories for each resource
	// subsystem. The function [cgroups.Manager.apply()] applies cgroup
	// configuration to the process with the specified pid.
	// It creates cgroup files for each subsytems and writes the pid
	// in the tasks file. We use the function to create all the required
	// cgroup files but not attach any "real" pid to the cgroup.
	if err := fsCgroupManager.Apply(0); err != nil {
		return fmt.Errorf("Failed to apply cgroup config for %v: %v", name, err)
	}
	return nil
}
<|endoftext|>


<commit_before>package namespace

import (
	"github.com/containerum/chkit/pkg/model"
)

var (
	_ model.TableRenderer = &Namespace{}
)

func (Namespace) TableHeaders() []string {
	return []string{"Label", "ID", "CPU", "MEM", "Age"}
}

func (namespace Namespace) TableRows() [][]string {
	return [][]string{{
		namespace.OwnerAndLabel(),
		namespace.ID,
		namespace.UsageCPU(),
		namespace.UsageMemory(),
		namespace.Age(),
	}}
}

func (namespace Namespace) RenderTable() string {
	return model.RenderTable(namespace)
}
<commit_msg>add access level to namespace table representation #138<commit_after>package namespace

import (
	"github.com/containerum/chkit/pkg/model"
)

var (
	_ model.TableRenderer = &Namespace{}
)

func (Namespace) TableHeaders() []string {
	return []string{"Label", "Access level", "ID", "CPU", "MEM", "Age"}
}

func (namespace Namespace) TableRows() [][]string {
	return [][]string{{
		namespace.OwnerAndLabel(),
		namespace.Access.String(),
		namespace.ID,
		namespace.UsageCPU(),
		namespace.UsageMemory(),
		namespace.Age(),
	}}
}

func (namespace Namespace) RenderTable() string {
	return model.RenderTable(namespace)
}
<|endoftext|>


<commit_before>package system

import (
	"fmt"
	"sync"

	"strings"

	"kego.io/kerr"
	"kego.io/kfmt"
)

var types struct {
	sync.RWMutex
	m map[string]*Type
}

func RegisterType(name string, typ *Type) {
	types.Lock()
	defer types.Unlock()
	if types.m == nil {
		types.m = make(map[string]*Type)
	}
	types.m[name] = typ
}
func UnregisterType(name string) {
	types.Lock()
	defer types.Unlock()
	if types.m == nil || name == "" {
		// Added the name == "" condition to make it
		// possible for a test to get in here
		return
	}
	delete(types.m, name)
}

// TODO: Perhaps this should not return a pointer if it will
// TODO: be used concurrently?
func GetType(name string) (*Type, bool) {
	types.RLock()
	defer types.RUnlock()
	t, ok := types.m[name]
	if !ok {
		return nil, false
	}
	return t, true
}

// TODO: Perhaps this should not return pointers if it will
// TODO: be used concurrently?
func GetAllTypesInPackage(path string) map[string]*Type {
	out := map[string]*Type{}
	types.RLock()
	defer types.RUnlock()
	for k, t := range types.m {
		if strings.HasPrefix(k, fmt.Sprintf("%s:", path)) {
			out[k] = t
		}
	}
	return out
}

func (t *Type) HasExtends() bool {
	// Only the actual system:object type should have an empty string here.
	return t.Extends.Value != ""
}

type nativeTypeClasses string

const (
	nativeValue      nativeTypeClasses = "value"
	nativeCollection nativeTypeClasses = "collection"
	nativeObject     nativeTypeClasses = "object"
)

func nativeTypeClass(nativeTypeString string) nativeTypeClasses {
	switch nativeTypeString {
	case "number", "string", "bool":
		return nativeValue
	case "map", "array":
		return nativeCollection
	default:
		return nativeObject
	}
}

func nativeGoType(jsonNativeType string) (string, error) {
	switch jsonNativeType {
	case "number":
		return "float64", nil
	case "string":
		return "string", nil
	case "bool":
		return "bool", nil
	default:
		return "", kerr.New("TXQIDRBJRH", nil, "nativeGoType", "Native type not found: %v", jsonNativeType)
	}
}

func (t *Type) IsNativeValue() bool {
	return nativeTypeClass(t.Native.Value) == nativeValue
}
func (t *Type) IsNativeCollection() bool {
	return nativeTypeClass(t.Native.Value) == nativeCollection
}
func (t *Type) IsNativeObject() bool {
	return nativeTypeClass(t.Native.Value) == nativeObject
}
func (t *Type) NativeValueGolangType() (string, error) {
	return nativeGoType(t.Native.Value)
}

func (t *Type) GoName() string {
	return IdToGoName(t.Id)
}

func (t *Type) FullName() string {
	return fmt.Sprintf("%s:%s", t.Context.Package, t.Id)
}

// GoTypeReference outputs a Go source code reference to the name of this type. If we're in
// the local package, it just outputs the name e.g. "Object". If we're in a different package,
// it looks up the alias of the package in the imports and appends that to the start.
// e.g. "system.Object".
func (t *Type) GoTypeReference(path string, imports map[string]string) (string, error) {
	return IdToGoReference(t.Context.Package, t.Id, path, imports)
}

func (t *Type) GoSyntax(path string, imports map[string]string) string {
	return kfmt.GoSyntax(path, imports, *t)
}

func (t *Type) Defaulter() (name string, property *Property, ok bool) {
	for name, prop := range t.Properties {
		if prop.Defaulter {
			return name, prop, true
		}
	}
	return "", nil, false
}
<commit_msg>Renamed to literal<commit_after>package system

import (
	"fmt"
	"sync"

	"strings"

	"kego.io/kerr"
	"kego.io/literal"
)

var types struct {
	sync.RWMutex
	m map[string]*Type
}

func RegisterType(name string, typ *Type) {
	types.Lock()
	defer types.Unlock()
	if types.m == nil {
		types.m = make(map[string]*Type)
	}
	types.m[name] = typ
}
func UnregisterType(name string) {
	types.Lock()
	defer types.Unlock()
	if types.m == nil || name == "" {
		// Added the name == "" condition to make it
		// possible for a test to get in here
		return
	}
	delete(types.m, name)
}

// TODO: Perhaps this should not return a pointer if it will
// TODO: be used concurrently?
func GetType(name string) (*Type, bool) {
	types.RLock()
	defer types.RUnlock()
	t, ok := types.m[name]
	if !ok {
		return nil, false
	}
	return t, true
}

// TODO: Perhaps this should not return pointers if it will
// TODO: be used concurrently?
func GetAllTypesInPackage(path string) map[string]*Type {
	out := map[string]*Type{}
	types.RLock()
	defer types.RUnlock()
	for k, t := range types.m {
		if strings.HasPrefix(k, fmt.Sprintf("%s:", path)) {
			out[k] = t
		}
	}
	return out
}

func (t *Type) HasExtends() bool {
	// Only the actual system:object type should have an empty string here.
	return t.Extends.Value != ""
}

type nativeTypeClasses string

const (
	nativeValue      nativeTypeClasses = "value"
	nativeCollection nativeTypeClasses = "collection"
	nativeObject     nativeTypeClasses = "object"
)

func nativeTypeClass(nativeTypeString string) nativeTypeClasses {
	switch nativeTypeString {
	case "number", "string", "bool":
		return nativeValue
	case "map", "array":
		return nativeCollection
	default:
		return nativeObject
	}
}

func nativeGoType(jsonNativeType string) (string, error) {
	switch jsonNativeType {
	case "number":
		return "float64", nil
	case "string":
		return "string", nil
	case "bool":
		return "bool", nil
	default:
		return "", kerr.New("TXQIDRBJRH", nil, "nativeGoType", "Native type not found: %v", jsonNativeType)
	}
}

func (t *Type) IsNativeValue() bool {
	return nativeTypeClass(t.Native.Value) == nativeValue
}
func (t *Type) IsNativeCollection() bool {
	return nativeTypeClass(t.Native.Value) == nativeCollection
}
func (t *Type) IsNativeObject() bool {
	return nativeTypeClass(t.Native.Value) == nativeObject
}
func (t *Type) NativeValueGolangType() (string, error) {
	return nativeGoType(t.Native.Value)
}

func (t *Type) GoName() string {
	return IdToGoName(t.Id)
}

func (t *Type) FullName() string {
	return fmt.Sprintf("%s:%s", t.Context.Package, t.Id)
}

// GoTypeReference outputs a Go source code reference to the name of this type. If we're in
// the local package, it just outputs the name e.g. "Object". If we're in a different package,
// it looks up the alias of the package in the imports and appends that to the start.
// e.g. "system.Object".
func (t *Type) GoTypeReference(path string, imports map[string]string) (string, error) {
	return IdToGoReference(t.Context.Package, t.Id, path, imports)
}

func (t *Type) GoSyntax(path string, imports map[string]string) string {
	return literal.GoSyntax(path, imports, *t)
}

func (t *Type) Defaulter() (name string, property *Property, ok bool) {
	for name, prop := range t.Properties {
		if prop.Defaulter {
			return name, prop, true
		}
	}
	return "", nil, false
}
<|endoftext|>


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

package packages

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"sync"
	"syscall"
	"unsafe"

	"golang.org/x/sys/unix"
)

func ioctl(fd, req, arg uintptr) (err error) {
	_, _, e1 := unix.Syscall(unix.SYS_IOCTL, fd, req, arg)
	if e1 != 0 {
		err = syscall.Errno(e1)
	}
	return
}

// This is used for anytime we need to parse YUM output.
// See https://bugzilla.redhat.com/show_bug.cgi?id=584525#c21
// TODO: We should probably look into a thin python shim we can
// interact with that the utilizes the yum libraries.
func runWithPty(cmd *exec.Cmd) ([]byte, []byte, error) {
	// Much of this logic was taken from, without the CGO stuff:
	// https://golang.org/src/os/signal/signal_cgo_test.go

	pty, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
	if err != nil {
		return nil, nil, err
	}
	defer pty.Close()

	// grantpt doesn't appear to be required anymore.

	// unlockpt
	var i int
	if err := ioctl(pty.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&i))); err != nil {
		return nil, nil, fmt.Errorf("error from ioctl TIOCSPTLCK: %v", err)
	}

	// ptsname
	var u uint32
	if err := ioctl(pty.Fd(), unix.TIOCGPTN, uintptr(unsafe.Pointer(&u))); err != nil {
		return nil, nil, fmt.Errorf("error from ioctl TIOCGPTN: %v", err)
	}
	path := filepath.Join("/dev/pts", strconv.Itoa(int(u)))

	tty, err := os.OpenFile(path, os.O_RDWR|syscall.O_NOCTTY, 0)
	if err != nil {
		return nil, nil, err
	}
	defer tty.Close()

	if err := unix.IoctlSetWinsize(int(pty.Fd()), syscall.TIOCSWINSZ, &unix.Winsize{Row: 1, Col: 500}); err != nil {
		return nil, nil, fmt.Errorf("error from IoctlSetWinsize: %v", err)
	}

	var stderr bytes.Buffer
	cmd.Stdin = tty
	cmd.Stdout = tty
	cmd.Stderr = &stderr
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Setctty: true,
		Setsid:  true,
		Ctty:    int(tty.Fd()),
	}

	var stdout bytes.Buffer
	var retErr error
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		input := bufio.NewReader(pty)
		for {
			b, err := input.ReadBytes('\n')
			if err != nil {
				if perr, ok := err.(*os.PathError); ok {
					err = perr.Err
				}
				if err != io.EOF && err != syscall.EIO {
					retErr = err
				}
				return
			}

			if _, err := stdout.Write(b); err != nil {
				retErr = err
				return
			}
		}
	}()

	err = cmd.Run()
	if err := tty.Close(); err != nil {
		return nil, nil, err
	}

	wg.Wait()
	// Exit code 0 means no updates, 1 probably means there are but we just didn't install them.
	if err == nil {
		return nil, nil, err
	}
	return stdout.Bytes(), stderr.Bytes(), retErr
}
<commit_msg>Fixed the runWithPty function to set ctty to child's filedesc (#389)<commit_after>//  Copyright 2019 Google Inc. All Rights Reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

package packages

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"sync"
	"syscall"
	"unsafe"

	"golang.org/x/sys/unix"
)

func ioctl(fd, req, arg uintptr) (err error) {
	_, _, e1 := unix.Syscall(unix.SYS_IOCTL, fd, req, arg)
	if e1 != 0 {
		err = syscall.Errno(e1)
	}
	return
}

// This is used for anytime we need to parse YUM output.
// See https://bugzilla.redhat.com/show_bug.cgi?id=584525#c21
// TODO: We should probably look into a thin python shim we can
// interact with that the utilizes the yum libraries.
func runWithPty(cmd *exec.Cmd) ([]byte, []byte, error) {
	// Much of this logic was taken from, without the CGO stuff:
	// https://golang.org/src/os/signal/signal_cgo_test.go

	pty, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
	if err != nil {
		return nil, nil, err
	}
	defer pty.Close()

	// grantpt doesn't appear to be required anymore.

	// unlockpt
	var i int
	if err := ioctl(pty.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&i))); err != nil {
		return nil, nil, fmt.Errorf("error from ioctl TIOCSPTLCK: %v", err)
	}

	// ptsname
	var u uint32
	if err := ioctl(pty.Fd(), unix.TIOCGPTN, uintptr(unsafe.Pointer(&u))); err != nil {
		return nil, nil, fmt.Errorf("error from ioctl TIOCGPTN: %v", err)
	}
	path := filepath.Join("/dev/pts", strconv.Itoa(int(u)))

	tty, err := os.OpenFile(path, os.O_RDWR|syscall.O_NOCTTY, 0)
	if err != nil {
		return nil, nil, err
	}
	defer tty.Close()

	if err := unix.IoctlSetWinsize(int(pty.Fd()), syscall.TIOCSWINSZ, &unix.Winsize{Row: 1, Col: 500}); err != nil {
		return nil, nil, fmt.Errorf("error from IoctlSetWinsize: %v", err)
	}

	var stderr bytes.Buffer
	cmd.Stdin = tty
	cmd.Stdout = tty
	cmd.Stderr = &stderr
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Setctty: true,
		Setsid:  true,
		Ctty:    0, // Stdin of the child process
	}

	var stdout bytes.Buffer
	var retErr error
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		input := bufio.NewReader(pty)
		for {
			b, err := input.ReadBytes('\n')
			if err != nil {
				if perr, ok := err.(*os.PathError); ok {
					err = perr.Err
				}
				if err != io.EOF && err != syscall.EIO {
					retErr = err
				}
				return
			}

			if _, err := stdout.Write(b); err != nil {
				retErr = err
				return
			}
		}
	}()

	cmdErr := cmd.Run()

	if err := tty.Close(); err != nil {
		return stdout.Bytes(), stderr.Bytes(), err

	}
	wg.Wait()

	if cmdErr != nil {
		// Yum returns non-zero exit values on non-error conditions.
		// Errors which are *not* in this category indicate failure.
		if _, ok := cmdErr.(*exec.ExitError); !ok {
			return stdout.Bytes(), stderr.Bytes(), cmdErr

		}
	}

	// Exit code 0 means no updates, 1 probably means there are but we just didn't install them.
	if cmdErr == nil {
		return nil, nil, nil
	}
	return stdout.Bytes(), stderr.Bytes(), retErr
}
<|endoftext|>