<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package cmd

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
	"github.com/vespa-engine/vespa/client/go/util"
	"github.com/vespa-engine/vespa/client/go/vespa"
	"github.com/vespa-engine/vespa/client/go/vespa/xml"
)

func init() {
	rootCmd.AddCommand(prodCmd)
	prodCmd.AddCommand(prodInitCmd)
	prodCmd.AddCommand(prodSubmitCmd)
}

var prodCmd = &cobra.Command{
	Use:   "prod",
	Short: "Deploy an application package to production in Vespa Cloud",
	Long: `Deploy an application package to production in Vespa Cloud.

Configure and deploy your application package to production in Vespa Cloud.`,
	Example: `$ vespa prod init
$ vespa prod submit`,
	DisableAutoGenTag: true,
	Run: func(cmd *cobra.Command, args []string) {
		// Root command does nothing
		cmd.Help()
		exitFunc(1)
	},
}

var prodInitCmd = &cobra.Command{
	Use:   "init",
	Short: "Modify service.xml and deployment.xml for production deployment",
	Long: `Modify service.xml and deployment.xml for production deployment.

Only basic deployment configuration is available through this command. For
advanced configuration see the relevant Vespa Cloud documentation and make
changes to deployment.xml and services.xml directly.

Reference:
https://cloud.vespa.ai/en/reference/services
https://cloud.vespa.ai/en/reference/deployment`,
	DisableAutoGenTag: true,
	Run: func(cmd *cobra.Command, args []string) {
		appSource := applicationSource(args)
		pkg, err := vespa.FindApplicationPackage(appSource, false)
		if err != nil {
			fatalErr(err)
			return
		}
		if pkg.IsZip() {
			fatalErrHint(fmt.Errorf("Cannot modify compressed application package %s", pkg.Path),
				"Try running 'mvn clean' and run this command again")
			return
		}

		deploymentXML, err := readDeploymentXML(pkg)
		if err != nil {
			fatalErr(err, "Could not read deployment.xml")
			return
		}
		servicesXML, err := readServicesXML(pkg)
		if err != nil {
			fatalErr(err, "A services.xml declaring your cluster(s) must exist")
			return
		}

		fmt.Fprint(stdout, "This will modify any existing ", color.Yellow("deployment.xml"), " and ", color.Yellow("services.xml"),
			"!\nBefore modification a backup of the original file will be created.\n\n")
		fmt.Fprint(stdout, "A default value is suggested (shown inside brackets) based on\nthe files' existing contents. Press enter to use it.\n\n")
		fmt.Fprint(stdout, "Abort the configuration at any time by pressing Ctrl-C. The\nfiles will remain untouched.\n\n")
		r := bufio.NewReader(stdin)
		deploymentXML = updateRegions(r, deploymentXML)
		servicesXML = updateNodes(r, servicesXML)

		fmt.Fprintln(stdout)
		if err := writeWithBackup(pkg, "deployment.xml", deploymentXML.String()); err != nil {
			fatalErr(err)
			return
		}
		if err := writeWithBackup(pkg, "services.xml", servicesXML.String()); err != nil {
			fatalErr(err)
			return
		}
	},
}

var prodSubmitCmd = &cobra.Command{
	Use:   "submit",
	Short: "Submit your application for production deployment",
	Long: `Submit your application for production deployment.

This commands uploads your application package to Vespa Cloud and deploys it to
the production zones specified in deployment.xml.

Nodes are allocated to your application according to resources specified in
services.xml.

While submitting an application from a local development environment is
supported, it's strongly recommended that production deployments are performed
by a continuous build system.

For more information about production deployments in Vespa Cloud see:
https://cloud.vespa.ai/en/getting-to-production
https://cloud.vespa.ai/en/automated-deployments`,
	DisableAutoGenTag: true,
	Example: `$ mvn package
$ vespa prod submit`,
	Run: func(cmd *cobra.Command, args []string) {
		target := getTarget()
		if target.Type() != "cloud" {
			fatalErr(fmt.Errorf("%s target cannot deploy to Vespa Cloud", target.Type()))
			return
		}
		appSource := applicationSource(args)
		pkg, err := vespa.FindApplicationPackage(appSource, true)
		if err != nil {
			fatalErr(err)
			return
		}
		cfg, err := LoadConfig()
		if err != nil {
			fatalErr(err, "Could not load config")
			return
		}
		if !pkg.HasDeployment() {
			fatalErrHint(fmt.Errorf("No deployment.xml found"), "Try creating one with vespa prod init")
			return
		}
		if !pkg.IsJava() {
			// TODO: Loosen this requirement when we start supporting applications with Java in production
			fatalErrHint(fmt.Errorf("No jar files found in %s", pkg.Path), "Only applications containing Java components are currently supported")
			return
		}
		isCI := os.Getenv("CI") != ""
		if !isCI {
			fmt.Fprintln(stderr, color.Yellow("Warning:"), "Submitting from a non-CI environment is discouraged")
			printErrHint(nil, "See https://cloud.vespa.ai/en/getting-to-production for best practices")
		}
		opts := getDeploymentOpts(cfg, pkg, target)
		if err := vespa.Submit(opts); err != nil {
			fatalErr(err, "Could not submit application for deployment")
		} else {
			printSuccess("Submitted ", color.Cyan(pkg.Path), " for deployment")
			log.Printf("See %s for deployment progress\n", color.Cyan(fmt.Sprintf("%s/tenant/%s/application/%s/prod/deployment",
				getConsoleURL(), opts.Deployment.Application.Tenant, opts.Deployment.Application.Application)))
		}
	},
}

func writeWithBackup(pkg vespa.ApplicationPackage, filename, contents string) error {
	dst := filepath.Join(pkg.Path, filename)
	if util.PathExists(dst) {
		data, err := ioutil.ReadFile(dst)
		if err != nil {
			return err
		}
		if bytes.Equal(data, []byte(contents)) {
			fmt.Fprintf(stdout, "Not writing %s: File is unchanged\n", color.Yellow(filename))
			return nil
		}
		renamed := false
		for i := 1; i <= 1000; i++ {
			bak := fmt.Sprintf("%s.%d.bak", dst, i)
			if !util.PathExists(bak) {
				fmt.Fprintf(stdout, "Backing up existing %s to %s\n", color.Yellow(filename), color.Yellow(bak))
				if err := os.Rename(dst, bak); err != nil {
					return err
				}
				renamed = true
				break
			}
		}
		if !renamed {
			return fmt.Errorf("could not find an unused backup name for %s", dst)
		}
	}
	fmt.Fprintf(stdout, "Writing %s\n", color.Green(dst))
	return ioutil.WriteFile(dst, []byte(contents), 0644)
}

func updateRegions(r *bufio.Reader, deploymentXML xml.Deployment) xml.Deployment {
	regions := promptRegions(r, deploymentXML)
	parts := strings.Split(regions, ",")
	regionElements := xml.Regions(parts...)
	if err := deploymentXML.Replace("prod", "region", regionElements); err != nil {
		fatalErr(err, "Could not update region elements in deployment.xml")
	}
	// TODO: Some sample apps come with production <test> elements, but not necessarily working production tests, we
	//       therefore remove <test> elements here.
	//       This can be improved by supporting <test> elements in xml package and allow specifying testing as part of
	//       region prompt, e.g. region1;test,region2
	if err := deploymentXML.Replace("prod", "test", nil); err != nil {
		fatalErr(err, "Could not remove test elements in deployment.xml")
	}
	return deploymentXML
}

func promptRegions(r *bufio.Reader, deploymentXML xml.Deployment) string {
	fmt.Fprintln(stdout, color.Cyan("> Deployment regions"))
	fmt.Fprintf(stdout, "Documentation: %s\n", color.Green("https://cloud.vespa.ai/en/reference/zones"))
	fmt.Fprintf(stdout, "Example: %s\n\n", color.Yellow("aws-us-east-1c,aws-us-west-2a"))
	var currentRegions []string
	for _, r := range deploymentXML.Prod.Regions {
		currentRegions = append(currentRegions, r.Name)
	}
	if len(deploymentXML.Instance) > 0 {
		for _, r := range deploymentXML.Instance[0].Prod.Regions {
			currentRegions = append(currentRegions, r.Name)
		}
	}
	validator := func(input string) error {
		regions := strings.Split(input, ",")
		for _, r := range regions {
			if !xml.IsProdRegion(r, getSystem()) {
				return fmt.Errorf("invalid region %s", r)
			}
		}
		return nil
	}
	return prompt(r, "Which regions do you wish to deploy in?", strings.Join(currentRegions, ","), validator)
}

func updateNodes(r *bufio.Reader, servicesXML xml.Services) xml.Services {
	for _, c := range servicesXML.Container {
		nodes := promptNodes(r, c.ID, c.Nodes)
		if err := servicesXML.Replace("container#"+c.ID, "nodes", nodes); err != nil {
			fatalErr(err)
			return xml.Services{}
		}
	}
	for _, c := range servicesXML.Content {
		nodes := promptNodes(r, c.ID, c.Nodes)
		if err := servicesXML.Replace("content#"+c.ID, "nodes", nodes); err != nil {
			fatalErr(err)
			return xml.Services{}
		}
	}
	return servicesXML
}

func promptNodes(r *bufio.Reader, clusterID string, defaultValue xml.Nodes) xml.Nodes {
	count := promptNodeCount(r, clusterID, defaultValue.Count)
	const autoSpec = "auto"
	defaultSpec := autoSpec
	resources := defaultValue.Resources
	if resources != nil {
		defaultSpec = defaultValue.Resources.String()
	}
	spec := promptResources(r, clusterID, defaultSpec)
	if spec == autoSpec {
		resources = nil
	} else {
		r, err := xml.ParseResources(spec)
		if err != nil {
			fatalErr(err) // Should not happen as resources have already been validated
			return xml.Nodes{}
		}
		resources = &r
	}
	return xml.Nodes{Count: count, Resources: resources}
}

func promptNodeCount(r *bufio.Reader, clusterID string, nodeCount string) string {
	fmt.Fprintln(stdout, color.Cyan("\n> Node count: "+clusterID+" cluster"))
	fmt.Fprintf(stdout, "Documentation: %s\n", color.Green("https://cloud.vespa.ai/en/reference/services"))
	fmt.Fprintf(stdout, "Example: %s\nExample: %s\n\n", color.Yellow("4"), color.Yellow("[2,8]"))
	validator := func(input string) error {
		_, _, err := xml.ParseNodeCount(input)
		return err
	}
	return prompt(r, fmt.Sprintf("How many nodes should the %s cluster have?", color.Cyan(clusterID)), nodeCount, validator)
}

func promptResources(r *bufio.Reader, clusterID string, resources string) string {
	fmt.Fprintln(stdout, color.Cyan("\n> Node resources: "+clusterID+" cluster"))
	fmt.Fprintf(stdout, "Documentation: %s\n", color.Green("https://cloud.vespa.ai/en/reference/services"))
	fmt.Fprintf(stdout, "Example: %s\nExample: %s\n\n", color.Yellow("auto"), color.Yellow("vcpu=4,memory=8Gb,disk=100Gb"))
	validator := func(input string) error {
		if input == "auto" {
			return nil
		}
		_, err := xml.ParseResources(input)
		return err
	}
	return prompt(r, fmt.Sprintf("Which resources should each node in the %s cluster have?", color.Cyan(clusterID)), resources, validator)
}

func readDeploymentXML(pkg vespa.ApplicationPackage) (xml.Deployment, error) {
	f, err := os.Open(filepath.Join(pkg.Path, "deployment.xml"))
	if errors.Is(err, os.ErrNotExist) {
		// Return a default value if there is no current deployment.xml
		return xml.DefaultDeployment, nil
	} else if err != nil {
		return xml.Deployment{}, err
	}
	defer f.Close()
	return xml.ReadDeployment(f)
}

func readServicesXML(pkg vespa.ApplicationPackage) (xml.Services, error) {
	f, err := os.Open(filepath.Join(pkg.Path, "services.xml"))
	if err != nil {
		return xml.Services{}, err
	}
	defer f.Close()
	return xml.ReadServices(f)
}

func prompt(r *bufio.Reader, question, defaultAnswer string, validator func(input string) error) string {
	var input string
	for input == "" {
		fmt.Fprint(stdout, question)
		if defaultAnswer != "" {
			fmt.Fprint(stdout, " [", color.Yellow(defaultAnswer), "]")
		}
		fmt.Fprint(stdout, " ")

		var err error
		input, err = r.ReadString('\n')
		if err != nil {
			fatalErr(err)
			return ""
		}
		input = strings.TrimSpace(input)
		if input == "" {
			input = defaultAnswer
		}

		if err := validator(input); err != nil {
			printErr(err)
			fmt.Fprintln(stderr)
			input = ""
		}
	}
	return input
}
<commit_msg>Tweak CD text<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package cmd

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
	"github.com/vespa-engine/vespa/client/go/util"
	"github.com/vespa-engine/vespa/client/go/vespa"
	"github.com/vespa-engine/vespa/client/go/vespa/xml"
)

func init() {
	rootCmd.AddCommand(prodCmd)
	prodCmd.AddCommand(prodInitCmd)
	prodCmd.AddCommand(prodSubmitCmd)
}

var prodCmd = &cobra.Command{
	Use:   "prod",
	Short: "Deploy an application package to production in Vespa Cloud",
	Long: `Deploy an application package to production in Vespa Cloud.

Configure and deploy your application package to production in Vespa Cloud.`,
	Example: `$ vespa prod init
$ vespa prod submit`,
	DisableAutoGenTag: true,
	Run: func(cmd *cobra.Command, args []string) {
		// Root command does nothing
		cmd.Help()
		exitFunc(1)
	},
}

var prodInitCmd = &cobra.Command{
	Use:   "init",
	Short: "Modify service.xml and deployment.xml for production deployment",
	Long: `Modify service.xml and deployment.xml for production deployment.

Only basic deployment configuration is available through this command. For
advanced configuration see the relevant Vespa Cloud documentation and make
changes to deployment.xml and services.xml directly.

Reference:
https://cloud.vespa.ai/en/reference/services
https://cloud.vespa.ai/en/reference/deployment`,
	DisableAutoGenTag: true,
	Run: func(cmd *cobra.Command, args []string) {
		appSource := applicationSource(args)
		pkg, err := vespa.FindApplicationPackage(appSource, false)
		if err != nil {
			fatalErr(err)
			return
		}
		if pkg.IsZip() {
			fatalErrHint(fmt.Errorf("Cannot modify compressed application package %s", pkg.Path),
				"Try running 'mvn clean' and run this command again")
			return
		}

		deploymentXML, err := readDeploymentXML(pkg)
		if err != nil {
			fatalErr(err, "Could not read deployment.xml")
			return
		}
		servicesXML, err := readServicesXML(pkg)
		if err != nil {
			fatalErr(err, "A services.xml declaring your cluster(s) must exist")
			return
		}

		fmt.Fprint(stdout, "This will modify any existing ", color.Yellow("deployment.xml"), " and ", color.Yellow("services.xml"),
			"!\nBefore modification a backup of the original file will be created.\n\n")
		fmt.Fprint(stdout, "A default value is suggested (shown inside brackets) based on\nthe files' existing contents. Press enter to use it.\n\n")
		fmt.Fprint(stdout, "Abort the configuration at any time by pressing Ctrl-C. The\nfiles will remain untouched.\n\n")
		r := bufio.NewReader(stdin)
		deploymentXML = updateRegions(r, deploymentXML)
		servicesXML = updateNodes(r, servicesXML)

		fmt.Fprintln(stdout)
		if err := writeWithBackup(pkg, "deployment.xml", deploymentXML.String()); err != nil {
			fatalErr(err)
			return
		}
		if err := writeWithBackup(pkg, "services.xml", servicesXML.String()); err != nil {
			fatalErr(err)
			return
		}
	},
}

var prodSubmitCmd = &cobra.Command{
	Use:   "submit",
	Short: "Submit your application for production deployment",
	Long: `Submit your application for production deployment.

This commands uploads your application package to Vespa Cloud and deploys it to
the production zones specified in deployment.xml.

Nodes are allocated to your application according to resources specified in
services.xml.

While submitting an application from a local development environment is
supported, it's strongly recommended that production deployments are performed
by a continuous build system.

For more information about production deployments in Vespa Cloud see:
https://cloud.vespa.ai/en/getting-to-production
https://cloud.vespa.ai/en/automated-deployments`,
	DisableAutoGenTag: true,
	Example: `$ mvn package
$ vespa prod submit`,
	Run: func(cmd *cobra.Command, args []string) {
		target := getTarget()
		if target.Type() != "cloud" {
			fatalErr(fmt.Errorf("%s target cannot deploy to Vespa Cloud", target.Type()))
			return
		}
		appSource := applicationSource(args)
		pkg, err := vespa.FindApplicationPackage(appSource, true)
		if err != nil {
			fatalErr(err)
			return
		}
		cfg, err := LoadConfig()
		if err != nil {
			fatalErr(err, "Could not load config")
			return
		}
		if !pkg.HasDeployment() {
			fatalErrHint(fmt.Errorf("No deployment.xml found"), "Try creating one with vespa prod init")
			return
		}
		if !pkg.IsJava() {
			// TODO: Loosen this requirement when we start supporting applications with Java in production
			fatalErrHint(fmt.Errorf("No jar files found in %s", pkg.Path), "Only applications containing Java components are currently supported")
			return
		}
		isCI := os.Getenv("CI") != ""
		if !isCI {
			fmt.Fprintln(stderr, color.Yellow("Warning:"), "We recommend doing this only from a CD job")
			printErrHint(nil, "See https://cloud.vespa.ai/en/getting-to-production")
		}
		opts := getDeploymentOpts(cfg, pkg, target)
		if err := vespa.Submit(opts); err != nil {
			fatalErr(err, "Could not submit application for deployment")
		} else {
			printSuccess("Submitted ", color.Cyan(pkg.Path), " for deployment")
			log.Printf("See %s for deployment progress\n", color.Cyan(fmt.Sprintf("%s/tenant/%s/application/%s/prod/deployment",
				getConsoleURL(), opts.Deployment.Application.Tenant, opts.Deployment.Application.Application)))
		}
	},
}

func writeWithBackup(pkg vespa.ApplicationPackage, filename, contents string) error {
	dst := filepath.Join(pkg.Path, filename)
	if util.PathExists(dst) {
		data, err := ioutil.ReadFile(dst)
		if err != nil {
			return err
		}
		if bytes.Equal(data, []byte(contents)) {
			fmt.Fprintf(stdout, "Not writing %s: File is unchanged\n", color.Yellow(filename))
			return nil
		}
		renamed := false
		for i := 1; i <= 1000; i++ {
			bak := fmt.Sprintf("%s.%d.bak", dst, i)
			if !util.PathExists(bak) {
				fmt.Fprintf(stdout, "Backing up existing %s to %s\n", color.Yellow(filename), color.Yellow(bak))
				if err := os.Rename(dst, bak); err != nil {
					return err
				}
				renamed = true
				break
			}
		}
		if !renamed {
			return fmt.Errorf("could not find an unused backup name for %s", dst)
		}
	}
	fmt.Fprintf(stdout, "Writing %s\n", color.Green(dst))
	return ioutil.WriteFile(dst, []byte(contents), 0644)
}

func updateRegions(r *bufio.Reader, deploymentXML xml.Deployment) xml.Deployment {
	regions := promptRegions(r, deploymentXML)
	parts := strings.Split(regions, ",")
	regionElements := xml.Regions(parts...)
	if err := deploymentXML.Replace("prod", "region", regionElements); err != nil {
		fatalErr(err, "Could not update region elements in deployment.xml")
	}
	// TODO: Some sample apps come with production <test> elements, but not necessarily working production tests, we
	//       therefore remove <test> elements here.
	//       This can be improved by supporting <test> elements in xml package and allow specifying testing as part of
	//       region prompt, e.g. region1;test,region2
	if err := deploymentXML.Replace("prod", "test", nil); err != nil {
		fatalErr(err, "Could not remove test elements in deployment.xml")
	}
	return deploymentXML
}

func promptRegions(r *bufio.Reader, deploymentXML xml.Deployment) string {
	fmt.Fprintln(stdout, color.Cyan("> Deployment regions"))
	fmt.Fprintf(stdout, "Documentation: %s\n", color.Green("https://cloud.vespa.ai/en/reference/zones"))
	fmt.Fprintf(stdout, "Example: %s\n\n", color.Yellow("aws-us-east-1c,aws-us-west-2a"))
	var currentRegions []string
	for _, r := range deploymentXML.Prod.Regions {
		currentRegions = append(currentRegions, r.Name)
	}
	if len(deploymentXML.Instance) > 0 {
		for _, r := range deploymentXML.Instance[0].Prod.Regions {
			currentRegions = append(currentRegions, r.Name)
		}
	}
	validator := func(input string) error {
		regions := strings.Split(input, ",")
		for _, r := range regions {
			if !xml.IsProdRegion(r, getSystem()) {
				return fmt.Errorf("invalid region %s", r)
			}
		}
		return nil
	}
	return prompt(r, "Which regions do you wish to deploy in?", strings.Join(currentRegions, ","), validator)
}

func updateNodes(r *bufio.Reader, servicesXML xml.Services) xml.Services {
	for _, c := range servicesXML.Container {
		nodes := promptNodes(r, c.ID, c.Nodes)
		if err := servicesXML.Replace("container#"+c.ID, "nodes", nodes); err != nil {
			fatalErr(err)
			return xml.Services{}
		}
	}
	for _, c := range servicesXML.Content {
		nodes := promptNodes(r, c.ID, c.Nodes)
		if err := servicesXML.Replace("content#"+c.ID, "nodes", nodes); err != nil {
			fatalErr(err)
			return xml.Services{}
		}
	}
	return servicesXML
}

func promptNodes(r *bufio.Reader, clusterID string, defaultValue xml.Nodes) xml.Nodes {
	count := promptNodeCount(r, clusterID, defaultValue.Count)
	const autoSpec = "auto"
	defaultSpec := autoSpec
	resources := defaultValue.Resources
	if resources != nil {
		defaultSpec = defaultValue.Resources.String()
	}
	spec := promptResources(r, clusterID, defaultSpec)
	if spec == autoSpec {
		resources = nil
	} else {
		r, err := xml.ParseResources(spec)
		if err != nil {
			fatalErr(err) // Should not happen as resources have already been validated
			return xml.Nodes{}
		}
		resources = &r
	}
	return xml.Nodes{Count: count, Resources: resources}
}

func promptNodeCount(r *bufio.Reader, clusterID string, nodeCount string) string {
	fmt.Fprintln(stdout, color.Cyan("\n> Node count: "+clusterID+" cluster"))
	fmt.Fprintf(stdout, "Documentation: %s\n", color.Green("https://cloud.vespa.ai/en/reference/services"))
	fmt.Fprintf(stdout, "Example: %s\nExample: %s\n\n", color.Yellow("4"), color.Yellow("[2,8]"))
	validator := func(input string) error {
		_, _, err := xml.ParseNodeCount(input)
		return err
	}
	return prompt(r, fmt.Sprintf("How many nodes should the %s cluster have?", color.Cyan(clusterID)), nodeCount, validator)
}

func promptResources(r *bufio.Reader, clusterID string, resources string) string {
	fmt.Fprintln(stdout, color.Cyan("\n> Node resources: "+clusterID+" cluster"))
	fmt.Fprintf(stdout, "Documentation: %s\n", color.Green("https://cloud.vespa.ai/en/reference/services"))
	fmt.Fprintf(stdout, "Example: %s\nExample: %s\n\n", color.Yellow("auto"), color.Yellow("vcpu=4,memory=8Gb,disk=100Gb"))
	validator := func(input string) error {
		if input == "auto" {
			return nil
		}
		_, err := xml.ParseResources(input)
		return err
	}
	return prompt(r, fmt.Sprintf("Which resources should each node in the %s cluster have?", color.Cyan(clusterID)), resources, validator)
}

func readDeploymentXML(pkg vespa.ApplicationPackage) (xml.Deployment, error) {
	f, err := os.Open(filepath.Join(pkg.Path, "deployment.xml"))
	if errors.Is(err, os.ErrNotExist) {
		// Return a default value if there is no current deployment.xml
		return xml.DefaultDeployment, nil
	} else if err != nil {
		return xml.Deployment{}, err
	}
	defer f.Close()
	return xml.ReadDeployment(f)
}

func readServicesXML(pkg vespa.ApplicationPackage) (xml.Services, error) {
	f, err := os.Open(filepath.Join(pkg.Path, "services.xml"))
	if err != nil {
		return xml.Services{}, err
	}
	defer f.Close()
	return xml.ReadServices(f)
}

func prompt(r *bufio.Reader, question, defaultAnswer string, validator func(input string) error) string {
	var input string
	for input == "" {
		fmt.Fprint(stdout, question)
		if defaultAnswer != "" {
			fmt.Fprint(stdout, " [", color.Yellow(defaultAnswer), "]")
		}
		fmt.Fprint(stdout, " ")

		var err error
		input, err = r.ReadString('\n')
		if err != nil {
			fatalErr(err)
			return ""
		}
		input = strings.TrimSpace(input)
		if input == "" {
			input = defaultAnswer
		}

		if err := validator(input); err != nil {
			printErr(err)
			fmt.Fprintln(stderr)
			input = ""
		}
	}
	return input
}
<|endoftext|>


<commit_before>package dns

// A structure for handling zone data

import (
	"radix"
)

// Zone represents a DNS zone.
type Zone struct {
	Origin       string // Origin of the zone
	*radix.Radix        // Zone data
}

// ZoneData holds all the RRs having their ownername equal to Name.
type ZoneData struct {
	Name string          // Domain name for this node
	RR   map[uint16][]RR // Map of the RR type to the RR
	// DNSSEC signatures for the RRsets
	Signatures []*RR_RRSIG
	// Almost always true, except for non-origin NS records (and accompanying glue)
	Authoritatve bool
}

// NewZone creates an initialized zone with Origin set origin.
func NewZone(origin string) *Zone {
	if origin == "" {
		origin = "."
	}
	if _, _, ok := IsDomainName(origin); !ok {
		return nil
	}
	z := new(Zone)
	z.Origin = Fqdn(origin)
	z.Radix = radix.New()
	return z
}

// Insert inserts an RR into the zone. Duplicate data overwrites the
// old data.
func (z *Zone) Insert(r RR) error {
	if !IsSubDomain(r.Header().Name, z.Origin) {
		return &Error{Err: "out of zone data", Name: r.Header().Name}
	}

	zd := z.Radix.Find(r.Header().Name)
	if zd == nil {
		zd := new(ZoneData)
		zd.Name = r.Header().Name
		zd.RR = make(map[uint16][]RR)
		zd.Signatures = make([]*RR_RRSIG, 0)
		switch t := r.Header().Rrtype; t {
		case TypeRRSIG:
			zd.Signatures = append(zd.Signatures, r.(*RR_RRSIG))
		default:
			zd.RR[t] = append(zd.RR[t], r)
			glueCheck(r)
		}
		z.Radix.Insert(r.Header().Name, zd)
		return
	}
	// Name already added
	switch t := r.Header().Rrtype; t {
	case TypeRRSIG:
		zd.Value.(*ZoneData).Signatures = append(zd.Value.(*ZoneData).Signatures, r.(*RR_RRSIG))
	default:
		zd.Value.(*ZoneData).RR[t] = append(zd.Value.(*ZoneData).RR[t], r)
	}
	return
}

func glueCheck(r RR) {
	if n, ok := r.(*RR_NS); ok {
		// Check if glue would be needed
		if CompareLabels(r.Header().Name, n.Ns) == LenLabels(r.Header().Name) {
			println("glue needed?", r.Header().Name, n.Ns)
		}
	}
}

func (z *Zone) Remove(r RR) {

}
<commit_msg>add glue detection<commit_after>package dns

// A structure for handling zone data

import (
	"radix"
)

// Zone represents a DNS zone.
type Zone struct {
	Origin       string // Origin of the zone
	*radix.Radix        // Zone data
}

// ZoneData holds all the RRs having their ownername equal to Name.
type ZoneData struct {
	Name string          // Domain name for this node
	RR   map[uint16][]RR // Map of the RR type to the RR
	// DNSSEC signatures for the RRsets
	Signatures []*RR_RRSIG
	// Always false, except for glue... TODO(mg)
	NonAuth bool
}

// NewZone creates an initialized zone with Origin set origin.
func NewZone(origin string) *Zone {
	if origin == "" {
		origin = "."
	}
	if _, _, ok := IsDomainName(origin); !ok {
		return nil
	}
	z := new(Zone)
	z.Origin = Fqdn(origin)
	z.Radix = radix.New()
	return z
}

// Insert inserts an RR into the zone. Duplicate data overwrites the
// old data.
func (z *Zone) Insert(r RR) error {
	if !IsSubDomain(r.Header().Name, z.Origin) {
		return &Error{Err: "out of zone data", Name: r.Header().Name}
	}

	zd := z.Radix.Find(r.Header().Name)
	if zd == nil {
		zd := new(ZoneData)
		zd.Name = r.Header().Name
		zd.RR = make(map[uint16][]RR)
		zd.Signatures = make([]*RR_RRSIG, 0)
		switch t := r.Header().Rrtype; t {
		case TypeRRSIG:
			zd.Signatures = append(zd.Signatures, r.(*RR_RRSIG))
		case TypeNS:
			// NS records with other names than z.Origin are non-auth
			if z.Header().Name != z.Origin {
				zd.NonAuth = true
			}
			fallthrough
		default:
			zd.RR[t] = append(zd.RR[t], r)
		}
		z.Radix.Insert(r.Header().Name, zd)
		return
	}
	// Name already added
	switch t := r.Header().Rrtype; t {
	case TypeRRSIG:
		zd.Value.(*ZoneData).Signatures = append(zd.Value.(*ZoneData).Signatures, r.(*RR_RRSIG))
	case TypeNS:
		// NS records with other names than z.Origin are non-auth
		if z.Header().Name != z.Origin {
			zd.NonAuth = true
		}
		fallthrough
	default:
		zd.Value.(*ZoneData).RR[t] = append(zd.Value.(*ZoneData).RR[t], r)
	}
	return
}

func (z *Zone) Remove(r RR) {

}
<|endoftext|>


<commit_before>package hashigo

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"

	"github.com/hashicorp/go-version"
)

var (
	versionRe = regexp.MustCompile(`v?(\d+\.\d+\.[^\s]+)`)
)

// Project represents a HashiCorp Go project and provides various operations
// around that.
type Project struct {
	Name       string
	InstallDir string
}

// Path returns the path to this project. This will check if the project
// binary is pre-installed in our installation directory and use that path.
// Otherwise, it will return the raw project name.
func (p *Project) Path() string {
	full := filepath.Join(p.InstallDir, p.Name, p.Name)
	if _, err := os.Stat(full); err == nil {
		return full
	}

	return p.Name
}

func (p *Project) Version() (*version.Version, error) {
	path := p.Path()
	if !filepath.IsAbs(path) {
		// Look for it on the path first if we don't have a full path to it
		_, err := exec.LookPath(path)
		if err != nil {
			if execErr, ok := err.(*exec.Error); ok && execErr.Err == exec.ErrNotFound {
				return nil, nil
			}

			return nil, err
		}
	}

	// Grab the version
	var buf bytes.Buffer
	cmd := exec.Command(path, "--version")
	cmd.Stdout = &buf
	if err := cmd.Run(); err != nil {
		return nil, err
	}

	// Match the version out
	matches := versionRe.FindStringSubmatch(buf.String())
	if len(matches) == 0 {
		return nil, fmt.Errorf("unable to find Vagrant version: %s", buf.String())
	}

	return version.NewVersion(matches[1])
}
<commit_msg>helper/hashigo: docs<commit_after>package hashigo

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"

	"github.com/hashicorp/go-version"
)

var (
	versionRe = regexp.MustCompile(`v?(\d+\.\d+\.[^\s]+)`)
)

// Project represents a HashiCorp Go project and provides various operations
// around that.
type Project struct {
	Name       string
	InstallDir string
}

// Path returns the path to this project. This will check if the project
// binary is pre-installed in our installation directory and use that path.
// Otherwise, it will return the raw project name.
func (p *Project) Path() string {
	full := filepath.Join(p.InstallDir, p.Name, p.Name)
	if _, err := os.Stat(full); err == nil {
		return full
	}

	return p.Name
}

// Version reads the version of this project.
func (p *Project) Version() (*version.Version, error) {
	path := p.Path()
	if !filepath.IsAbs(path) {
		// Look for it on the path first if we don't have a full path to it
		_, err := exec.LookPath(path)
		if err != nil {
			if execErr, ok := err.(*exec.Error); ok && execErr.Err == exec.ErrNotFound {
				return nil, nil
			}

			return nil, err
		}
	}

	// Grab the version
	var buf bytes.Buffer
	cmd := exec.Command(path, "--version")
	cmd.Stdout = &buf
	if err := cmd.Run(); err != nil {
		return nil, err
	}

	// Match the version out
	matches := versionRe.FindStringSubmatch(buf.String())
	if len(matches) == 0 {
		return nil, fmt.Errorf("unable to find Vagrant version: %s", buf.String())
	}

	return version.NewVersion(matches[1])
}
<|endoftext|>


<commit_before>package spi

import (
	"fmt"
	. "github.com/balzaczyy/golucene/core/index/model"
	"github.com/balzaczyy/golucene/core/store"
)

// index/SegmentCommitInfo.java

// Embeds a [read-only] SegmentInfo and adds per-commit fields.
type SegmentCommitInfo struct {
	// The SegmentInfo that we wrap.
	Info *SegmentInfo
	// How many deleted docs in the segment:
	delCount int
	// Generation number of the live docs file (-1 if there are no deletes yet)
	delGen int64
	// Normally 1+delGen, unless an exception was hit on last attempt to write:
	nextWriteDelGen int64

	fieldInfosGen int64

	nextWriteFieldInfosGen int64

	docValuesGen int64

	nextWriteDocValuesGen int64

	dvUpdatesFiles map[int]map[string]bool

	fieldInfosFiles map[string]bool

	genUpdatesFiles map[int64]map[string]bool

	sizeInBytes int64 // volatile

	// NOTE: only used by in-RAM by IW to track buffered deletes;
	// this is never written to/read from the Directory
	BufferedUpdatesGen int64
}

func NewSegmentCommitInfo(info *SegmentInfo,
	delCount int, delGen, fieldInfosGen, docValuesGen int64) *SegmentCommitInfo {

	ans := &SegmentCommitInfo{
		Info:                   info,
		delCount:               delCount,
		delGen:                 delGen,
		nextWriteDelGen:        1,
		fieldInfosGen:          fieldInfosGen,
		nextWriteFieldInfosGen: 1,
		docValuesGen:           docValuesGen,
		nextWriteDocValuesGen:  1,
		dvUpdatesFiles:         make(map[int]map[string]bool),
		fieldInfosFiles:        make(map[string]bool),
		genUpdatesFiles:        make(map[int64]map[string]bool),
		sizeInBytes:            -1,
	}
	if delGen != -1 {
		ans.nextWriteDelGen = delGen + 1
	}
	if fieldInfosGen != -1 {
		ans.nextWriteFieldInfosGen = fieldInfosGen + 1
	}
	if docValuesGen != -1 {
		ans.nextWriteDocValuesGen = docValuesGen + 1
	}
	return ans
}

/* Called when we succeed in writing deletes */
func (info *SegmentCommitInfo) AdvanceDelGen() {
	info.delGen, info.nextWriteDelGen = info.nextWriteDelGen, info.delGen+1
	info.sizeInBytes = -1
}

/*
Called if there was an error while writing deletes, so that we don't
try to write to the same file more than once.
*/
func (info *SegmentCommitInfo) AdvanceNextWriteDelGen() {
	info.nextWriteDelGen++
}

/*
Returns total size in bytes of all files for this segment.

NOTE: This value is not correct for 3.0 segments that have shared
docstores. To get correct value, upgrade.
*/
func (si *SegmentCommitInfo) SizeInBytes() (sum int64, err error) {
	if si.sizeInBytes == -1 {
		sum = 0
		for _, fileName := range si.Files() {
			d, err := si.Info.Dir.FileLength(fileName)
			if err != nil {
				return 0, err
			}
			sum += d
		}
		si.sizeInBytes = sum
	}
	return si.sizeInBytes, nil
}

// Returns all files in use by this segment.
func (si *SegmentCommitInfo) Files() []string {
	// Start from the wrapped info's files:
	files := make(map[string]bool)
	for name, _ := range si.Info.Files() {
		files[name] = true
	}

	// Must separately add any live docs files
	for _, name := range si.Info.Codec().(Codec).LiveDocsFormat().Files(si) {
		files[name] = true
	}

	// Must separately add any per-gen updates files. This can go away
	// when we get rid of genUpdatesFiles (6.0)
	for _, names := range si.genUpdatesFiles {
		for name, _ := range names {
			files[name] = true
		}
	}

	// must separately add any field updates files
	for _, names := range si.dvUpdatesFiles {
		for name, _ := range names {
			files[name] = true
		}
	}

	// must separately add fieldInfos files
	for name, _ := range si.fieldInfosFiles {
		files[name] = true
	}

	ans := make([]string, 0, len(files))
	for s, _ := range files {
		ans = append(ans, s)
	}
	return ans
}

func (si *SegmentCommitInfo) SetBufferedUpdatesGen(v int64) {
	si.BufferedUpdatesGen = v
	si.sizeInBytes = -1
}

// Returns true if there are any deletions for the segment at this
// commit.
func (si *SegmentCommitInfo) HasDeletions() bool {
	return si.delGen != -1
}

/* Returns the next available generation numbre of the live docs file. */
func (si *SegmentCommitInfo) NextDelGen() int64 {
	return si.nextWriteDelGen
}

/* Returns generation number of the live docs file or -1 if there are no deletes yet. */
func (si *SegmentCommitInfo) DelGen() int64 {
	return si.delGen
}

/* Returns the number of deleted docs in the segment. */
func (si *SegmentCommitInfo) DelCount() int {
	return si.delCount
}

func (si *SegmentCommitInfo) SetDelCount(delCount int) {
	assert2(delCount >= 0 && delCount <= si.Info.DocCount(),
		"invalid delCount=%v (docCount=%v)", delCount, si.Info.DocCount())
	si.delCount = delCount
}

func (si *SegmentCommitInfo) StringOf(dir store.Directory, pendingDelCount int) string {
	panic("not implemented yet")
	return si.Info.StringOf(dir, si.delCount+pendingDelCount)
}

func (si *SegmentCommitInfo) String() string {
	panic("not implemented yet")
	s := si.Info.StringOf(si.Info.Dir, si.delCount)
	if si.delGen != -1 {
		s = fmt.Sprintf("%v:delGen=%v", s, si.delGen)
	}
	return s
}

func (si *SegmentCommitInfo) Clone() *SegmentCommitInfo {
	panic("not implemented yet")
	// Not clear that we need ot carry over nextWriteDelGen (i.e. do we
	// ever clone after a failed write and before the next successful
	// write?), but just do it to be safe:
	return &SegmentCommitInfo{
		Info:            si.Info,
		delCount:        si.delCount,
		delGen:          si.delGen,
		nextWriteDelGen: si.nextWriteDelGen,
	}
}
<commit_msg>implement SegmentCommitInfo.toString()<commit_after>package spi

import (
	"fmt"
	. "github.com/balzaczyy/golucene/core/index/model"
	"github.com/balzaczyy/golucene/core/store"
)

// index/SegmentCommitInfo.java

// Embeds a [read-only] SegmentInfo and adds per-commit fields.
type SegmentCommitInfo struct {
	// The SegmentInfo that we wrap.
	Info *SegmentInfo
	// How many deleted docs in the segment:
	delCount int
	// Generation number of the live docs file (-1 if there are no deletes yet)
	delGen int64
	// Normally 1+delGen, unless an exception was hit on last attempt to write:
	nextWriteDelGen int64

	fieldInfosGen int64

	nextWriteFieldInfosGen int64

	docValuesGen int64

	nextWriteDocValuesGen int64

	dvUpdatesFiles map[int]map[string]bool

	fieldInfosFiles map[string]bool

	genUpdatesFiles map[int64]map[string]bool

	sizeInBytes int64 // volatile

	// NOTE: only used by in-RAM by IW to track buffered deletes;
	// this is never written to/read from the Directory
	BufferedUpdatesGen int64
}

func NewSegmentCommitInfo(info *SegmentInfo,
	delCount int, delGen, fieldInfosGen, docValuesGen int64) *SegmentCommitInfo {

	ans := &SegmentCommitInfo{
		Info:                   info,
		delCount:               delCount,
		delGen:                 delGen,
		nextWriteDelGen:        1,
		fieldInfosGen:          fieldInfosGen,
		nextWriteFieldInfosGen: 1,
		docValuesGen:           docValuesGen,
		nextWriteDocValuesGen:  1,
		dvUpdatesFiles:         make(map[int]map[string]bool),
		fieldInfosFiles:        make(map[string]bool),
		genUpdatesFiles:        make(map[int64]map[string]bool),
		sizeInBytes:            -1,
	}
	if delGen != -1 {
		ans.nextWriteDelGen = delGen + 1
	}
	if fieldInfosGen != -1 {
		ans.nextWriteFieldInfosGen = fieldInfosGen + 1
	}
	if docValuesGen != -1 {
		ans.nextWriteDocValuesGen = docValuesGen + 1
	}
	return ans
}

/* Called when we succeed in writing deletes */
func (info *SegmentCommitInfo) AdvanceDelGen() {
	info.delGen, info.nextWriteDelGen = info.nextWriteDelGen, info.delGen+1
	info.sizeInBytes = -1
}

/*
Called if there was an error while writing deletes, so that we don't
try to write to the same file more than once.
*/
func (info *SegmentCommitInfo) AdvanceNextWriteDelGen() {
	info.nextWriteDelGen++
}

/*
Returns total size in bytes of all files for this segment.

NOTE: This value is not correct for 3.0 segments that have shared
docstores. To get correct value, upgrade.
*/
func (si *SegmentCommitInfo) SizeInBytes() (sum int64, err error) {
	if si.sizeInBytes == -1 {
		sum = 0
		for _, fileName := range si.Files() {
			d, err := si.Info.Dir.FileLength(fileName)
			if err != nil {
				return 0, err
			}
			sum += d
		}
		si.sizeInBytes = sum
	}
	return si.sizeInBytes, nil
}

// Returns all files in use by this segment.
func (si *SegmentCommitInfo) Files() []string {
	// Start from the wrapped info's files:
	files := make(map[string]bool)
	for name, _ := range si.Info.Files() {
		files[name] = true
	}

	// Must separately add any live docs files
	for _, name := range si.Info.Codec().(Codec).LiveDocsFormat().Files(si) {
		files[name] = true
	}

	// Must separately add any per-gen updates files. This can go away
	// when we get rid of genUpdatesFiles (6.0)
	for _, names := range si.genUpdatesFiles {
		for name, _ := range names {
			files[name] = true
		}
	}

	// must separately add any field updates files
	for _, names := range si.dvUpdatesFiles {
		for name, _ := range names {
			files[name] = true
		}
	}

	// must separately add fieldInfos files
	for name, _ := range si.fieldInfosFiles {
		files[name] = true
	}

	ans := make([]string, 0, len(files))
	for s, _ := range files {
		ans = append(ans, s)
	}
	return ans
}

func (si *SegmentCommitInfo) SetBufferedUpdatesGen(v int64) {
	si.BufferedUpdatesGen = v
	si.sizeInBytes = -1
}

// Returns true if there are any deletions for the segment at this
// commit.
func (si *SegmentCommitInfo) HasDeletions() bool {
	return si.delGen != -1
}

/* Returns the next available generation numbre of the live docs file. */
func (si *SegmentCommitInfo) NextDelGen() int64 {
	return si.nextWriteDelGen
}

/* Returns generation number of the live docs file or -1 if there are no deletes yet. */
func (si *SegmentCommitInfo) DelGen() int64 {
	return si.delGen
}

/* Returns the number of deleted docs in the segment. */
func (si *SegmentCommitInfo) DelCount() int {
	return si.delCount
}

func (si *SegmentCommitInfo) SetDelCount(delCount int) {
	assert2(delCount >= 0 && delCount <= si.Info.DocCount(),
		"invalid delCount=%v (docCount=%v)", delCount, si.Info.DocCount())
	si.delCount = delCount
}

func (si *SegmentCommitInfo) StringOf(dir store.Directory, pendingDelCount int) string {
	s := si.Info.StringOf(dir, si.delCount+pendingDelCount)
	var sDelGen, sFieldInfosGen, sDocValuesGen string
	if si.delGen != -1 {
		sDelGen = fmt.Sprintf(":delGen=%v", si.delGen)
	}
	if si.fieldInfosGen != -1 {
		sFieldInfosGen = fmt.Sprintf(":fieldInfosGen=%v", si.fieldInfosGen)
	}
	if si.docValuesGen != -1 {
		sDocValuesGen = fmt.Sprintf(":dvGen=%v", si.docValuesGen)
	}
	return fmt.Sprintf("%v%v%v%v", s, sDelGen, sFieldInfosGen, sDocValuesGen)
}

func (si *SegmentCommitInfo) String() string {
	panic("not implemented yet")
	s := si.Info.StringOf(si.Info.Dir, si.delCount)
	if si.delGen != -1 {
		s = fmt.Sprintf("%v:delGen=%v", s, si.delGen)
	}
	return s
}

func (si *SegmentCommitInfo) Clone() *SegmentCommitInfo {
	panic("not implemented yet")
	// Not clear that we need ot carry over nextWriteDelGen (i.e. do we
	// ever clone after a failed write and before the next successful
	// write?), but just do it to be safe:
	return &SegmentCommitInfo{
		Info:            si.Info,
		delCount:        si.delCount,
		delGen:          si.delGen,
		nextWriteDelGen: si.nextWriteDelGen,
	}
}
<|endoftext|>


<commit_before>package client

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"
	"strconv"
)

// NomadServer is connection parameters to a nomad server
type NomadServer struct {
	Address string
	Port    int
}

// Details represents a json object in a nomad job
type Details struct {
	Running int `json:"running"`
}

// Summary represents a json object in a nomad job
type Summary struct {
	Details Details `json:"server"`
}

// JobSummary represents a json object in a nomad job
type JobSummary struct {
	Summary Summary `json:"Summary"`
}

// Job is a representation of nomad job
type Job struct {
	Name       string     `json:"Name"`
	Priority   int        `json:"Priority"`
	Status     string     `json:"status"`
	JobSummary JobSummary `json:"JobSummary"`
}

// Host is a representation of a nomad client node
type Host struct {
	ID    string `json:"ID"`
	Name  string `json:"Name"`
	Drain bool   `json:"Drain"`
}

var httpClient = &http.Client{Timeout: 5 * time.Second}

// Jobs will parse the json representation from the nomad rest api
func Jobs(nomad *NomadServer) []Job {
	jobs := make([]Job, 0)
	decodeJSON(url(nomad)+"/v1/jobs", &jobs)
	return jobs
}

// Hosts will parse the json representation from the nomad rest api
func Hosts(nomad *NomadServer) []Host {
	hosts := make([]Host, 0)
	decodeJSON(url(nomad)+"/v1/nodes", &hosts)
	return hosts
}

func Drain(nomad *NomadServer, id string, enable bool) string {
        resp, _ := httpClient.Post(url(nomad) + "/v1/node/" + id + "/drain?enable=" + strconv.FormatBool(enable), "application/json", nil)
        return resp.Status
}

func url(nomad *NomadServer) string {
	return fmt.Sprintf("http://%v:%v", nomad.Address, nomad.Port)
}

func decodeJSON(url string, target interface{}) error {
	r, err := httpClient.Get(url)
	if err != nil {
		return err
	}
	defer r.Body.Close()
	return json.NewDecoder(r.Body).Decode(target)
}
<commit_msg>Adding alloc to nomad client<commit_after>package client

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// NomadServer is connection parameters to a nomad server
type NomadServer struct {
	Address string
	Port    int
}

// Details represents a json object in a nomad job
type Details struct {
	Running int `json:"running"`
}

// Summary represents a json object in a nomad job
type Summary struct {
	Details *Details `json:"server"`
}

// JobSummary represents a json object in a nomad job
type JobSummary struct {
	Summary *Summary `json:"Summary"`
}

// Job is a representation of nomad job
type Job struct {
	Name       string      `json:"Name"`
	Priority   int         `json:"Priority"`
	Status     string      `json:"status"`
	JobSummary *JobSummary `json:"JobSummary"`
}

// Task represents an allocated nomad task
type Task struct {
	State string `json:"State"`
}

// Alloc is a representation of a nomad allocation
type Alloc struct {
	ID           string          `json:"ID"`
	JobID        string          `json:"JobID"`
	NodeID       string          `json:"NodeID"`
	Name         string          `json:"Name"`
	ClientStatus string          `json:"ClientStatus"`
	Tasks        map[string]Task `json:"TaskStates"`
}

// Host is a representation of a nomad client node
type Host struct {
	ID    string `json:"ID"`
	Name  string `json:"Name"`
	Drain bool   `json:"Drain"`
}

// JobNotFound indicates that a Job search failed
type JobNotFound struct {
	Name string
}

// AllocNotFound indicates a missing allocation for a Job
type AllocNotFound struct {
	Jobname  string
	Hostname string
}

var httpClient = &http.Client{Timeout: 5 * time.Second}

// Jobs will parse the json representation from the nomad rest api
// /v1/jobs
func Jobs(nomad *NomadServer) []Job {
	jobs := make([]Job, 0)
	decodeJSON(url(nomad)+"/v1/jobs", &jobs)
	return jobs
}

// FindJob will parse the json representation and find the supplied job name
func FindJob(nomad *NomadServer, name string) (*Job, error) {
	jobs := Jobs(nomad)
	for _, job := range jobs {
		if job.Name == name {
			return &job, nil
		}
	}
	return &Job{}, &JobNotFound{Name: name}
}

func (e *JobNotFound) Error() string {
	return fmt.Sprintf("Unable to find job name: %v", e.Name)
}

// Hosts will parse the json representation from the nomad rest api
// /v1/nodes
func Hosts(nomad *NomadServer) []Host {
	hosts := make([]Host, 0)
	decodeJSON(url(nomad)+"/v1/nodes", &hosts)
	return hosts
}

// Drain will inform nomad to remove all allocations from that host
func Drain(nomad *NomadServer, id string, enable bool) string {
	resp, _ := httpClient.Post(url(nomad)+"/v1/node/"+id+"/drain?enable="+strconv.FormatBool(enable), "application/json", nil)
	return resp.Status
}

// Allocs will parse the json representation from the nomad rest api
// /v1/allocations
func Allocs(nomad *NomadServer) []Alloc {
	allocs := make([]Alloc, 0)
	decodeJSON(url(nomad)+"/v1/allocations", &allocs)
	return allocs
}

// FindAlloc will search through the Allocs on a provided Host to look for the
// allocations that match the provided Job
func FindAlloc(nomad *NomadServer, job *Job, host *Host) (*Alloc, error) {
	allocs := Allocs(nomad)
	for _, alloc := range allocs {
		if alloc.NodeID == host.ID && strings.Contains(alloc.Name, job.Name) {
			return &alloc, nil
		}
	}
	return &Alloc{}, &AllocNotFound{Hostname: host.Name, Jobname: job.Name}
}

// CheckTaskStates will return whether all of the tasks for an Alloc are
// in the state provided
func (alloc *Alloc) CheckTaskStates(state string) bool {
	for k := range alloc.Tasks {
		task := alloc.Tasks[k]
		if task.State != state {
			return false
		}
	}
	return true
}

func (e *AllocNotFound) Error() string {
	return fmt.Sprintf("Unable to find '%v' job on '%v' host.", e.Jobname, e.Hostname)
}

func url(nomad *NomadServer) string {
	return fmt.Sprintf("http://%v:%v", nomad.Address, nomad.Port)
}

func decodeJSON(url string, target interface{}) error {
	r, err := httpClient.Get(url)
	if err != nil {
		return err
	}
	defer r.Body.Close()
	return json.NewDecoder(r.Body).Decode(target)
}
<|endoftext|>


<commit_before>/*
Copyright 2015 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 watch

import (
	"io/ioutil"
	"testing"
)

func TestFileWatcher(t *testing.T) {
	file, err := ioutil.TempFile("", "fw")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	defer file.Close()
	count := 0
	fw, err := NewFileWatcher(file.Name(), func() {
		count++
		if count != 1 {
			t.Fatalf("expected 1 but returned %v", count)
		}
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	defer fw.Close()
	if count != 0 {
		t.Fatalf("expected 0 but returned %v", count)
	}
	ioutil.WriteFile(file.Name(), []byte{}, 0644)
}
<commit_msg>Fix a data race in TestFileWatcher (#24).<commit_after>/*
Copyright 2015 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 watch

import (
	"io/ioutil"
	"os"
	"testing"
	"time"
)

func prepareTimeout() chan bool {
	timeoutChan := make(chan bool, 1)
	go func() {
		time.Sleep(1 * time.Second)
		timeoutChan <- true
	}()
	return timeoutChan
}

func TestFileWatcher(t *testing.T) {
	file, err := ioutil.TempFile("", "fw")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	defer file.Close()
	defer os.Remove(file.Name())
	count := 0
	events := make(chan bool, 10)
	fw, err := NewFileWatcher(file.Name(), func() {
		count++
		if count != 1 {
			t.Fatalf("expected 1 but returned %v", count)
		}
		events <- true
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	defer fw.Close()
	timeoutChan := prepareTimeout()
	select {
	case <-events:
		t.Fatalf("expected no events before writing a file")
	case <-timeoutChan:
	}
	ioutil.WriteFile(file.Name(), []byte{}, 0644)
	select {
	case <-events:
	case <-timeoutChan:
		t.Fatalf("expected an event shortly after writing a file")
	}
}
<|endoftext|>


<commit_before>package networkwebsockets

import (
	"log"
	"testing"
)

func createClient(t *testing.T, urlStr string) *NetworkWebSocketClient {
	client, _, err := Dial(urlStr)
	if err != nil {
		t.Fatalf("Dial: ", err)
	}
	return client
}

func getClientId(client *NetworkWebSocketClient) string {
	// Request client's peer id
	client.SendStatusRequest()
	// Wait for response
	message := <-client.Status
	// Return client's peer id
	return message.Target
}

func checkConnect(t *testing.T, message NetworkWebSocketWireMessage, expectedTarget string) {
	if message.Target != expectedTarget {
		t.Fatalf("connect=%s, want %s", message.Target, expectedTarget)
	}
}

func checkDisconnect(t *testing.T, message NetworkWebSocketWireMessage, expectedTarget string) {
	if message.Target != expectedTarget {
		t.Fatalf("disconnect=%s, want %s", message.Target, expectedTarget)
	}
}

func checkBroadcast(t *testing.T, payload string, sender *NetworkWebSocketClient, receivers []*NetworkWebSocketClient) {
	// send broadcast message from sender
	sender.SendBroadcastData(payload)

	// check broadcast message arrived at all receivers
	for _, receiver := range receivers {
		message := <-receiver.Broadcast
		if message.Payload != payload {
			t.Fatalf("broadcast=%s, want %s", message.Payload, payload)
		}
	}
}

func checkMessage(t *testing.T, payload string, targetId string, sender *NetworkWebSocketClient, receiver *NetworkWebSocketClient) {
	if targetId == "" {
		t.Fatalf("No target identifier provided")
	}

	// send broadcast message from sender
	sender.SendMessageData(payload, targetId)

	// check broadcast message arrived at all receivers
	message := <-receiver.Message
	if message.Payload != payload {
		t.Fatalf("message=%s, want %s", message.Payload, payload)
	}
}

// TEST CASES

func Test_SameProxyClients(t *testing.T) {

	service := NewNetworkWebSocketService("localhost", 20100)
	_ = service.Start()

	// Create new Network Web Socket channel peers
	client1 := createClient(t, "ws://localhost:20100/myexampleservice")
	client2 := createClient(t, "ws://localhost:20100/myexampleservice")
	client3 := createClient(t, "ws://localhost:20100/myexampleservice")

	// Test status messaging (+ store client ids for future tests)
	client1Id := getClientId(client1)
	client2Id := getClientId(client2)
	client3Id := getClientId(client3)

	// Test connect messaging
	checkConnect(t, <-client1.Connect, client2Id)
	checkConnect(t, <-client1.Connect, client3Id)
	checkConnect(t, <-client2.Connect, client1Id)
	checkConnect(t, <-client2.Connect, client3Id)
	checkConnect(t, <-client3.Connect, client1Id)
	checkConnect(t, <-client3.Connect, client2Id)

	// Test broadcast messaging
	checkBroadcast(t, "hello world 1", client1, []*NetworkWebSocketClient{client2, client3})
	checkBroadcast(t, "hello world 2", client2, []*NetworkWebSocketClient{client1, client3})
	checkBroadcast(t, "hello world 3", client3, []*NetworkWebSocketClient{client1, client2})

	// Test direct messaging
	checkMessage(t, "direct message 1", client2Id, client1, client2)
	checkMessage(t, "direct message 2", client3Id, client1, client3)
	checkMessage(t, "direct message 3", client1Id, client2, client1)
	checkMessage(t, "direct message 4", client3Id, client2, client3)
	checkMessage(t, "direct message 5", client1Id, client3, client1)
	checkMessage(t, "direct message 6", client2Id, client3, client2)

	// Test disconnect messaging
	client1.Close()
	checkDisconnect(t, <-client2.Disconnect, client1Id)
	checkDisconnect(t, <-client3.Disconnect, client1Id)

	client2.Close()
	checkDisconnect(t, <-client3.Disconnect, client2Id)

	client3.Close()
}

func Test_MultipleProxyClients(t *testing.T) {

	service1 := NewNetworkWebSocketService("localhost", 20200)
	_ = service1.Start()

	service2 := NewNetworkWebSocketService("localhost", 20300)
	_ = service2.Start()

	// Create new Network Web Socket channel peers
	client1 := createClient(t, "ws://localhost:20200/testService2")
	client2 := createClient(t, "ws://localhost:20300/testService2")
	client3 := createClient(t, "ws://localhost:20300/testService2")

	// Test status messaging (+ store client ids for future tests)
	client1Id := getClientId(client1)
	client2Id := getClientId(client2)
	client3Id := getClientId(client3)

	log.Println("Waiting for Network Web Socket proxies to discover and connect to each other...")

	// Test connect messaging
	checkConnect(t, <-client1.Connect, client2Id)
	checkConnect(t, <-client1.Connect, client3Id)
	checkConnect(t, <-client2.Connect, client3Id)
	checkConnect(t, <-client2.Connect, client1Id)
	checkConnect(t, <-client3.Connect, client2Id)
	checkConnect(t, <-client3.Connect, client1Id)

	// Test broadcast messaging
	checkBroadcast(t, "hello world 1", client1, []*NetworkWebSocketClient{client2, client3})
	checkBroadcast(t, "hello world 2", client2, []*NetworkWebSocketClient{client1, client3})
	checkBroadcast(t, "hello world 3", client3, []*NetworkWebSocketClient{client1, client2})

	// Test direct messaging
	checkMessage(t, "direct message 1", client2Id, client1, client2)
	checkMessage(t, "direct message 2", client3Id, client1, client3)
	checkMessage(t, "direct message 3", client1Id, client2, client1)
	checkMessage(t, "direct message 4", client3Id, client2, client3)
	checkMessage(t, "direct message 5", client1Id, client3, client1)
	checkMessage(t, "direct message 6", client2Id, client3, client2)

	// Test disconnect messaging
	client1.Close()
	checkDisconnect(t, <-client2.Disconnect, client1Id)
	checkDisconnect(t, <-client3.Disconnect, client1Id)

	client2.Close()
	checkDisconnect(t, <-client3.Disconnect, client2Id)

	client3.Close()
}
<commit_msg>Improve shutdown of network websocket proxies in test cases<commit_after>package networkwebsockets

import (
	"log"
	"testing"
)

func createClient(t testing.TB, urlStr string) *NetworkWebSocketClient {
	client, _, err := Dial(urlStr)
	if err != nil {
		t.Fatalf("Dial: ", err)
	}
	return client
}

func getClientId(client *NetworkWebSocketClient) string {
	// Request client's peer id
	client.SendStatusRequest()
	// Wait for response
	message := <-client.Status
	// Return client's peer id
	return message.Target
}

func checkConnect(t testing.TB, message NetworkWebSocketWireMessage, expectedTarget string) {
	if message.Target != expectedTarget {
		t.Fatalf("connect=%s, want %s", message.Target, expectedTarget)
	}
}

func checkDisconnect(t testing.TB, message NetworkWebSocketWireMessage, expectedTarget string) {
	if message.Target != expectedTarget {
		t.Fatalf("disconnect=%s, want %s", message.Target, expectedTarget)
	}
}

func checkBroadcast(t testing.TB, payload string, sender *NetworkWebSocketClient, receivers []*NetworkWebSocketClient) {
	// send broadcast message from sender
	sender.SendBroadcastData(payload)

	// check broadcast message arrived at all receivers
	for _, receiver := range receivers {
		message := <-receiver.Broadcast
		if message.Payload != payload {
			t.Fatalf("broadcast=%s, want %s", message.Payload, payload)
		}
	}
}

func checkMessage(t testing.TB, payload string, targetId string, sender *NetworkWebSocketClient, receiver *NetworkWebSocketClient) {
	if targetId == "" {
		t.Fatalf("No target identifier provided")
	}

	// send broadcast message from sender
	sender.SendMessageData(payload, targetId)

	// check broadcast message arrived at all receivers
	message := <-receiver.Message
	if message.Payload != payload {
		t.Fatalf("message=%s, want %s", message.Payload, payload)
	}
}

// TEST CASES

func TestSameProxyClients(t *testing.T) {

	service := NewNetworkWebSocketService("localhost", 21000)
	_ = service.Start()

	// Create new Network Web Socket channel peers
	client1 := createClient(t, "ws://localhost:21000/testservice1")
	client2 := createClient(t, "ws://localhost:21000/testservice1")
	client3 := createClient(t, "ws://localhost:21000/testservice1")

	// Test status messaging (+ store client ids for future tests)
	client1Id := getClientId(client1)
	client2Id := getClientId(client2)
	client3Id := getClientId(client3)

	// Test connect messaging
	checkConnect(t, <-client1.Connect, client2Id)
	checkConnect(t, <-client1.Connect, client3Id)
	checkConnect(t, <-client2.Connect, client1Id)
	checkConnect(t, <-client2.Connect, client3Id)
	checkConnect(t, <-client3.Connect, client1Id)
	checkConnect(t, <-client3.Connect, client2Id)

	// Test broadcast messaging
	checkBroadcast(t, "hello world 1", client1, []*NetworkWebSocketClient{client2, client3})
	checkBroadcast(t, "hello world 2", client2, []*NetworkWebSocketClient{client1, client3})
	checkBroadcast(t, "hello world 3", client3, []*NetworkWebSocketClient{client1, client2})

	// Test direct messaging
	checkMessage(t, "direct message 1", client2Id, client1, client2)
	checkMessage(t, "direct message 2", client3Id, client1, client3)
	checkMessage(t, "direct message 3", client1Id, client2, client1)
	checkMessage(t, "direct message 4", client3Id, client2, client3)
	checkMessage(t, "direct message 5", client1Id, client3, client1)
	checkMessage(t, "direct message 6", client2Id, client3, client2)

	// Test disconnect messaging
	client1.Close()
	checkDisconnect(t, <-client2.Disconnect, client1Id)
	checkDisconnect(t, <-client3.Disconnect, client1Id)

	client2.Close()
	checkDisconnect(t, <-client3.Disconnect, client2Id)

	client3.Close()

	go service.Stop()

	<-service.StopNotify()
}

func TestMultipleProxyClients(t *testing.T) {

	service1 := NewNetworkWebSocketService("localhost", 21000)
	_ = service1.Start()

	service2 := NewNetworkWebSocketService("localhost", 21001)
	_ = service2.Start()

	// Create new Network Web Socket channel peers
	client1 := createClient(t, "ws://localhost:21000/testservice2")
	client2 := createClient(t, "ws://localhost:21001/testservice2")
	client3 := createClient(t, "ws://localhost:21001/testservice2")

	// Test status messaging (+ store client ids for future tests)
	client1Id := getClientId(client1)
	client2Id := getClientId(client2)
	client3Id := getClientId(client3)

	log.Println("Waiting for Network Web Socket proxies to discover and connect to each other...")

	// Test connect messaging
	checkConnect(t, <-client1.Connect, client2Id)
	checkConnect(t, <-client1.Connect, client3Id)
	checkConnect(t, <-client2.Connect, client3Id)
	checkConnect(t, <-client2.Connect, client1Id)
	checkConnect(t, <-client3.Connect, client2Id)
	checkConnect(t, <-client3.Connect, client1Id)

	// Test broadcast messaging
	checkBroadcast(t, "hello world 1", client1, []*NetworkWebSocketClient{client2, client3})
	checkBroadcast(t, "hello world 2", client2, []*NetworkWebSocketClient{client1, client3})
	checkBroadcast(t, "hello world 3", client3, []*NetworkWebSocketClient{client1, client2})

	// Test direct messaging
	checkMessage(t, "direct message 1", client2Id, client1, client2)
	checkMessage(t, "direct message 2", client3Id, client1, client3)
	checkMessage(t, "direct message 3", client1Id, client2, client1)
	checkMessage(t, "direct message 4", client3Id, client2, client3)
	checkMessage(t, "direct message 5", client1Id, client3, client1)
	checkMessage(t, "direct message 6", client2Id, client3, client2)

	// Test disconnect messaging
	client1.Close()
	checkDisconnect(t, <-client2.Disconnect, client1Id)
	checkDisconnect(t, <-client3.Disconnect, client1Id)

	client2.Close()
	checkDisconnect(t, <-client3.Disconnect, client2Id)

	client3.Close()

	go func() {
		service1.Stop()
		service2.Stop()
	}()

	<-service1.StopNotify()
	<-service2.StopNotify()
}
<|endoftext|>


<commit_before>/*
Copyright 2018 The Knative Authors

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

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

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

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"
	"sync"
	"time"

	"github.com/kelseyhightower/envconfig"
	"go.uber.org/zap"

	// Injection related imports.
	kubeclient "knative.dev/pkg/client/injection/kube/client"
	"knative.dev/pkg/injection"
	"knative.dev/serving/pkg/activator"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"

	network "knative.dev/networking/pkg"
	"knative.dev/pkg/configmap"
	configmapinformer "knative.dev/pkg/configmap/informer"
	"knative.dev/pkg/controller"
	"knative.dev/pkg/injection/sharedmain"
	pkglogging "knative.dev/pkg/logging"
	"knative.dev/pkg/logging/logkey"
	"knative.dev/pkg/metrics"
	pkgnet "knative.dev/pkg/network"
	"knative.dev/pkg/profiling"
	"knative.dev/pkg/signals"
	"knative.dev/pkg/system"
	"knative.dev/pkg/tracing"
	tracingconfig "knative.dev/pkg/tracing/config"
	"knative.dev/pkg/version"
	"knative.dev/pkg/websocket"
	activatorconfig "knative.dev/serving/pkg/activator/config"
	activatorhandler "knative.dev/serving/pkg/activator/handler"
	activatornet "knative.dev/serving/pkg/activator/net"
	asmetrics "knative.dev/serving/pkg/autoscaler/metrics"
	pkghttp "knative.dev/serving/pkg/http"
	"knative.dev/serving/pkg/logging"
	"knative.dev/serving/pkg/networking"
)

const (
	component = "activator"

	// The port on which autoscaler WebSocket server listens.
	autoscalerPort = ":8080"
)

type config struct {
	PodName string `split_words:"true" required:"true"`
	PodIP   string `split_words:"true" required:"true"`

	// These are here to allow configuring higher values of keep-alive for larger environments.
	// TODO: run loadtests using these flags to determine optimal default values.
	MaxIdleProxyConns        int `split_words:"true" default:"1000"`
	MaxIdleProxyConnsPerHost int `split_words:"true" default:"100"`
}

func main() {
	// Set up a context that we can cancel to tell informers and other subprocesses to stop.
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Report stats on Go memory usage every 30 seconds.
	metrics.MemStatsOrDie(ctx)

	cfg := injection.ParseAndGetRESTConfigOrDie()

	log.Printf("Registering %d clients", len(injection.Default.GetClients()))
	log.Printf("Registering %d informer factories", len(injection.Default.GetInformerFactories()))
	log.Printf("Registering %d informers", len(injection.Default.GetInformers()))

	ctx, informers := injection.Default.SetupInformers(ctx, cfg)

	var env config
	if err := envconfig.Process("", &env); err != nil {
		log.Fatal("Failed to process env: ", err)
	}

	kubeClient := kubeclient.Get(ctx)

	// We sometimes startup faster than we can reach kube-api. Poll on failure to prevent us terminating
	var err error
	if perr := wait.PollImmediate(time.Second, 60*time.Second, func() (bool, error) {
		if err = version.CheckMinimumVersion(kubeClient.Discovery()); err != nil {
			log.Print("Failed to get k8s version ", err)
		}
		return err == nil, nil
	}); perr != nil {
		log.Fatal("Timed out attempting to get k8s version: ", err)
	}

	// Set up our logger.
	loggingConfig, err := sharedmain.GetLoggingConfig(ctx)
	if err != nil {
		log.Fatal("Error loading/parsing logging configuration: ", err)
	}

	logger, atomicLevel := pkglogging.NewLoggerFromConfig(loggingConfig, component)
	logger = logger.With(zap.String(logkey.ControllerType, component),
		zap.String(logkey.Pod, env.PodName))
	ctx = pkglogging.WithLogger(ctx, logger)
	defer flush(logger)

	// Run informers instead of starting them from the factory to prevent the sync hanging because of empty handler.
	if err := controller.StartInformers(ctx.Done(), informers...); err != nil {
		logger.Fatalw("Failed to start informers", zap.Error(err))
	}

	logger.Info("Starting the knative activator")

	// Create the transport used by both the activator->QP probe and the proxy.
	// It's important that the throttler and the activatorhandler share this
	// transport so that throttler probe connections can be reused after probing
	// (via keep-alive) to send real requests, avoiding needing an extra
	// reconnect for the first request after the probe succeeds.
	logger.Debugf("MaxIdleProxyConns: %d, MaxIdleProxyConnsPerHost: %d", env.MaxIdleProxyConns, env.MaxIdleProxyConnsPerHost)
	transport := pkgnet.NewProxyAutoTransport(env.MaxIdleProxyConns, env.MaxIdleProxyConnsPerHost)

	// Fetch networking configuration to determine whether EnableMeshPodAddressability
	// is enabled or not.
	networkCM, err := kubeclient.Get(ctx).CoreV1().ConfigMaps(system.Namespace()).Get(ctx, network.ConfigName, metav1.GetOptions{})
	if err != nil {
		logger.Fatalw("Failed to fetch network config", zap.Error(err))
	}
	networkConfig, err := network.NewConfigFromConfigMap(networkCM)
	if err != nil {
		logger.Fatalw("Failed to construct network config", zap.Error(err))
	}

	// Start throttler.
	throttler := activatornet.NewThrottler(ctx, env.PodIP)
	go throttler.Run(ctx, transport, networkConfig.EnableMeshPodAddressability, networkConfig.MeshCompatibilityMode)

	oct := tracing.NewOpenCensusTracer(tracing.WithExporterFull(networking.ActivatorServiceName, env.PodIP, logger))

	tracerUpdater := configmap.TypeFilter(&tracingconfig.Config{})(func(name string, value interface{}) {
		cfg := value.(*tracingconfig.Config)
		if err := oct.ApplyConfig(cfg); err != nil {
			logger.Errorw("Unable to apply open census tracer config", zap.Error(err))
			return
		}
	})

	// Set up our config store
	configMapWatcher := configmapinformer.NewInformedWatcher(kubeClient, system.Namespace())
	configStore := activatorconfig.NewStore(logger, tracerUpdater)
	configStore.WatchConfigs(configMapWatcher)

	statCh := make(chan []asmetrics.StatMessage)
	defer close(statCh)

	// Open a WebSocket connection to the autoscaler.
	autoscalerEndpoint := "ws://" + pkgnet.GetServiceHostname("autoscaler", system.Namespace()) + autoscalerPort
	logger.Info("Connecting to Autoscaler at ", autoscalerEndpoint)
	statSink := websocket.NewDurableSendingConnection(autoscalerEndpoint, logger)
	defer statSink.Shutdown()
	go activator.ReportStats(logger, statSink, statCh)

	// Create and run our concurrency reporter
	concurrencyReporter := activatorhandler.NewConcurrencyReporter(ctx, env.PodName, statCh)
	go concurrencyReporter.Run(ctx.Done())

	// Create activation handler chain
	// Note: innermost handlers are specified first, ie. the last handler in the chain will be executed first
	ah := activatorhandler.New(ctx, throttler, transport, networkConfig.EnableMeshPodAddressability, logger)
	ah = concurrencyReporter.Handler(ah)
	ah = activatorhandler.NewTracingHandler(ah)
	reqLogHandler, err := pkghttp.NewRequestLogHandler(ah, logging.NewSyncFileWriter(os.Stdout), "",
		requestLogTemplateInputGetter, false /*enableProbeRequestLog*/)
	if err != nil {
		logger.Fatalw("Unable to create request log handler", zap.Error(err))
	}
	ah = reqLogHandler

	// NOTE: MetricHandler is being used as the outermost handler of the meaty bits. We're not interested in measuring
	// the healthchecks or probes.
	ah = activatorhandler.NewMetricHandler(env.PodName, ah)
	ah = activatorhandler.NewContextHandler(ctx, ah, configStore)

	// Network probe handlers.
	ah = &activatorhandler.ProbeHandler{NextHandler: ah}
	ah = network.NewProbeHandler(ah)

	// Set up our health check based on the health of stat sink and environmental factors.
	sigCtx, sigCancel := context.WithCancel(context.Background())
	hc := newHealthCheck(sigCtx, logger, statSink)
	ah = &activatorhandler.HealthHandler{HealthCheck: hc, NextHandler: ah, Logger: logger}

	profilingHandler := profiling.NewHandler(logger, false)
	// Watch the logging config map and dynamically update logging levels.
	configMapWatcher.Watch(pkglogging.ConfigMapName(), pkglogging.UpdateLevelFromConfigMap(logger, atomicLevel, component))

	// Watch the observability config map
	configMapWatcher.Watch(metrics.ConfigMapName(),
		metrics.ConfigMapWatcher(ctx, component, nil /* SecretFetcher */, logger),
		updateRequestLogFromConfigMap(logger, reqLogHandler),
		profilingHandler.UpdateFromConfigMap)

	if err = configMapWatcher.Start(ctx.Done()); err != nil {
		logger.Fatalw("Failed to start configuration manager", zap.Error(err))
	}

	servers := map[string]*http.Server{
		"http1":   pkgnet.NewServer(":"+strconv.Itoa(networking.BackendHTTPPort), ah),
		"h2c":     pkgnet.NewServer(":"+strconv.Itoa(networking.BackendHTTP2Port), ah),
		"profile": profiling.NewServer(profilingHandler),
	}

	errCh := make(chan error, len(servers))
	for name, server := range servers {
		go func(name string, s *http.Server) {
			// Don't forward ErrServerClosed as that indicates we're already shutting down.
			if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
				errCh <- fmt.Errorf("%s server failed: %w", name, err)
			}
		}(name, server)
	}

	sigCh := signals.SetupSignalHandler()

	// Wait for the signal to drain.
	select {
	case <-sigCh:
		logger.Info("Received SIGTERM")
		// Send a signal to let readiness probes start failing.
		sigCancel()
	case err := <-errCh:
		logger.Errorw("Failed to run HTTP server", zap.Error(err))
	}

	// The drain has started (we are now failing readiness probes).  Let the effects of this
	// propagate so that new requests are no longer routed our way.
	logger.Infof("Sleeping %v to allow K8s propagation of non-ready state", pkgnet.DefaultDrainTimeout)
	time.Sleep(pkgnet.DefaultDrainTimeout)
	logger.Info("Done waiting, shutting down servers.")

	// Drain outstanding requests, and stop accepting new ones.
	for _, server := range servers {
		server.Shutdown(context.Background())
	}
	logger.Info("Servers shutdown.")
}

func newHealthCheck(sigCtx context.Context, logger *zap.SugaredLogger, statSink *websocket.ManagedConnection) func() error {
	once := sync.Once{}
	return func() error {
		select {
		// When we get SIGTERM (sigCtx done), let readiness probes start failing.
		case <-sigCtx.Done():
			once.Do(func() {
				logger.Info("Signal context canceled")
			})
			return errors.New("received SIGTERM from kubelet")
		default:
			logger.Debug("No signal yet.")
			return statSink.Status()
		}
	}
}

func flush(logger *zap.SugaredLogger) {
	logger.Sync()
	os.Stdout.Sync()
	os.Stderr.Sync()
	metrics.FlushExporter()
}
<commit_msg>Directly use signals.NewContext rather than cancelling context on signal (#12419)<commit_after>/*
Copyright 2018 The Knative Authors

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

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

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

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"
	"sync"
	"time"

	"github.com/kelseyhightower/envconfig"
	"go.uber.org/zap"

	// Injection related imports.
	kubeclient "knative.dev/pkg/client/injection/kube/client"
	"knative.dev/pkg/injection"
	"knative.dev/serving/pkg/activator"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"

	network "knative.dev/networking/pkg"
	"knative.dev/pkg/configmap"
	configmapinformer "knative.dev/pkg/configmap/informer"
	"knative.dev/pkg/controller"
	"knative.dev/pkg/injection/sharedmain"
	pkglogging "knative.dev/pkg/logging"
	"knative.dev/pkg/logging/logkey"
	"knative.dev/pkg/metrics"
	pkgnet "knative.dev/pkg/network"
	"knative.dev/pkg/profiling"
	"knative.dev/pkg/signals"
	"knative.dev/pkg/system"
	"knative.dev/pkg/tracing"
	tracingconfig "knative.dev/pkg/tracing/config"
	"knative.dev/pkg/version"
	"knative.dev/pkg/websocket"
	activatorconfig "knative.dev/serving/pkg/activator/config"
	activatorhandler "knative.dev/serving/pkg/activator/handler"
	activatornet "knative.dev/serving/pkg/activator/net"
	asmetrics "knative.dev/serving/pkg/autoscaler/metrics"
	pkghttp "knative.dev/serving/pkg/http"
	"knative.dev/serving/pkg/logging"
	"knative.dev/serving/pkg/networking"
)

const (
	component = "activator"

	// The port on which autoscaler WebSocket server listens.
	autoscalerPort = ":8080"
)

type config struct {
	PodName string `split_words:"true" required:"true"`
	PodIP   string `split_words:"true" required:"true"`

	// These are here to allow configuring higher values of keep-alive for larger environments.
	// TODO: run loadtests using these flags to determine optimal default values.
	MaxIdleProxyConns        int `split_words:"true" default:"1000"`
	MaxIdleProxyConnsPerHost int `split_words:"true" default:"100"`
}

func main() {
	// Set up a context that we can cancel to tell informers and other subprocesses to stop.
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Report stats on Go memory usage every 30 seconds.
	metrics.MemStatsOrDie(ctx)

	cfg := injection.ParseAndGetRESTConfigOrDie()

	log.Printf("Registering %d clients", len(injection.Default.GetClients()))
	log.Printf("Registering %d informer factories", len(injection.Default.GetInformerFactories()))
	log.Printf("Registering %d informers", len(injection.Default.GetInformers()))

	ctx, informers := injection.Default.SetupInformers(ctx, cfg)

	var env config
	if err := envconfig.Process("", &env); err != nil {
		log.Fatal("Failed to process env: ", err)
	}

	kubeClient := kubeclient.Get(ctx)

	// We sometimes startup faster than we can reach kube-api. Poll on failure to prevent us terminating
	var err error
	if perr := wait.PollImmediate(time.Second, 60*time.Second, func() (bool, error) {
		if err = version.CheckMinimumVersion(kubeClient.Discovery()); err != nil {
			log.Print("Failed to get k8s version ", err)
		}
		return err == nil, nil
	}); perr != nil {
		log.Fatal("Timed out attempting to get k8s version: ", err)
	}

	// Set up our logger.
	loggingConfig, err := sharedmain.GetLoggingConfig(ctx)
	if err != nil {
		log.Fatal("Error loading/parsing logging configuration: ", err)
	}

	logger, atomicLevel := pkglogging.NewLoggerFromConfig(loggingConfig, component)
	logger = logger.With(zap.String(logkey.ControllerType, component),
		zap.String(logkey.Pod, env.PodName))
	ctx = pkglogging.WithLogger(ctx, logger)
	defer flush(logger)

	// Run informers instead of starting them from the factory to prevent the sync hanging because of empty handler.
	if err := controller.StartInformers(ctx.Done(), informers...); err != nil {
		logger.Fatalw("Failed to start informers", zap.Error(err))
	}

	logger.Info("Starting the knative activator")

	// Create the transport used by both the activator->QP probe and the proxy.
	// It's important that the throttler and the activatorhandler share this
	// transport so that throttler probe connections can be reused after probing
	// (via keep-alive) to send real requests, avoiding needing an extra
	// reconnect for the first request after the probe succeeds.
	logger.Debugf("MaxIdleProxyConns: %d, MaxIdleProxyConnsPerHost: %d", env.MaxIdleProxyConns, env.MaxIdleProxyConnsPerHost)
	transport := pkgnet.NewProxyAutoTransport(env.MaxIdleProxyConns, env.MaxIdleProxyConnsPerHost)

	// Fetch networking configuration to determine whether EnableMeshPodAddressability
	// is enabled or not.
	networkCM, err := kubeclient.Get(ctx).CoreV1().ConfigMaps(system.Namespace()).Get(ctx, network.ConfigName, metav1.GetOptions{})
	if err != nil {
		logger.Fatalw("Failed to fetch network config", zap.Error(err))
	}
	networkConfig, err := network.NewConfigFromConfigMap(networkCM)
	if err != nil {
		logger.Fatalw("Failed to construct network config", zap.Error(err))
	}

	// Start throttler.
	throttler := activatornet.NewThrottler(ctx, env.PodIP)
	go throttler.Run(ctx, transport, networkConfig.EnableMeshPodAddressability, networkConfig.MeshCompatibilityMode)

	oct := tracing.NewOpenCensusTracer(tracing.WithExporterFull(networking.ActivatorServiceName, env.PodIP, logger))

	tracerUpdater := configmap.TypeFilter(&tracingconfig.Config{})(func(name string, value interface{}) {
		cfg := value.(*tracingconfig.Config)
		if err := oct.ApplyConfig(cfg); err != nil {
			logger.Errorw("Unable to apply open census tracer config", zap.Error(err))
			return
		}
	})

	// Set up our config store
	configMapWatcher := configmapinformer.NewInformedWatcher(kubeClient, system.Namespace())
	configStore := activatorconfig.NewStore(logger, tracerUpdater)
	configStore.WatchConfigs(configMapWatcher)

	statCh := make(chan []asmetrics.StatMessage)
	defer close(statCh)

	// Open a WebSocket connection to the autoscaler.
	autoscalerEndpoint := "ws://" + pkgnet.GetServiceHostname("autoscaler", system.Namespace()) + autoscalerPort
	logger.Info("Connecting to Autoscaler at ", autoscalerEndpoint)
	statSink := websocket.NewDurableSendingConnection(autoscalerEndpoint, logger)
	defer statSink.Shutdown()
	go activator.ReportStats(logger, statSink, statCh)

	// Create and run our concurrency reporter
	concurrencyReporter := activatorhandler.NewConcurrencyReporter(ctx, env.PodName, statCh)
	go concurrencyReporter.Run(ctx.Done())

	// Create activation handler chain
	// Note: innermost handlers are specified first, ie. the last handler in the chain will be executed first
	ah := activatorhandler.New(ctx, throttler, transport, networkConfig.EnableMeshPodAddressability, logger)
	ah = concurrencyReporter.Handler(ah)
	ah = activatorhandler.NewTracingHandler(ah)
	reqLogHandler, err := pkghttp.NewRequestLogHandler(ah, logging.NewSyncFileWriter(os.Stdout), "",
		requestLogTemplateInputGetter, false /*enableProbeRequestLog*/)
	if err != nil {
		logger.Fatalw("Unable to create request log handler", zap.Error(err))
	}
	ah = reqLogHandler

	// NOTE: MetricHandler is being used as the outermost handler of the meaty bits. We're not interested in measuring
	// the healthchecks or probes.
	ah = activatorhandler.NewMetricHandler(env.PodName, ah)
	ah = activatorhandler.NewContextHandler(ctx, ah, configStore)

	// Network probe handlers.
	ah = &activatorhandler.ProbeHandler{NextHandler: ah}
	ah = network.NewProbeHandler(ah)

	// Set up our health check based on the health of stat sink and environmental factors.
	sigCtx := signals.NewContext()
	hc := newHealthCheck(sigCtx, logger, statSink)
	ah = &activatorhandler.HealthHandler{HealthCheck: hc, NextHandler: ah, Logger: logger}

	profilingHandler := profiling.NewHandler(logger, false)
	// Watch the logging config map and dynamically update logging levels.
	configMapWatcher.Watch(pkglogging.ConfigMapName(), pkglogging.UpdateLevelFromConfigMap(logger, atomicLevel, component))

	// Watch the observability config map
	configMapWatcher.Watch(metrics.ConfigMapName(),
		metrics.ConfigMapWatcher(ctx, component, nil /* SecretFetcher */, logger),
		updateRequestLogFromConfigMap(logger, reqLogHandler),
		profilingHandler.UpdateFromConfigMap)

	if err = configMapWatcher.Start(ctx.Done()); err != nil {
		logger.Fatalw("Failed to start configuration manager", zap.Error(err))
	}

	servers := map[string]*http.Server{
		"http1":   pkgnet.NewServer(":"+strconv.Itoa(networking.BackendHTTPPort), ah),
		"h2c":     pkgnet.NewServer(":"+strconv.Itoa(networking.BackendHTTP2Port), ah),
		"profile": profiling.NewServer(profilingHandler),
	}

	errCh := make(chan error, len(servers))
	for name, server := range servers {
		go func(name string, s *http.Server) {
			// Don't forward ErrServerClosed as that indicates we're already shutting down.
			if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
				errCh <- fmt.Errorf("%s server failed: %w", name, err)
			}
		}(name, server)
	}

	// Wait for the signal to drain.
	select {
	case <-sigCtx.Done():
		logger.Info("Received SIGTERM")
	case err := <-errCh:
		logger.Errorw("Failed to run HTTP server", zap.Error(err))
	}

	// The drain has started (we are now failing readiness probes).  Let the effects of this
	// propagate so that new requests are no longer routed our way.
	logger.Infof("Sleeping %v to allow K8s propagation of non-ready state", pkgnet.DefaultDrainTimeout)
	time.Sleep(pkgnet.DefaultDrainTimeout)
	logger.Info("Done waiting, shutting down servers.")

	// Drain outstanding requests, and stop accepting new ones.
	for _, server := range servers {
		server.Shutdown(context.Background())
	}
	logger.Info("Servers shutdown.")
}

func newHealthCheck(sigCtx context.Context, logger *zap.SugaredLogger, statSink *websocket.ManagedConnection) func() error {
	once := sync.Once{}
	return func() error {
		select {
		// When we get SIGTERM (sigCtx done), let readiness probes start failing.
		case <-sigCtx.Done():
			once.Do(func() {
				logger.Info("Signal context canceled")
			})
			return errors.New("received SIGTERM from kubelet")
		default:
			logger.Debug("No signal yet.")
			return statSink.Status()
		}
	}
}

func flush(logger *zap.SugaredLogger) {
	logger.Sync()
	os.Stdout.Sync()
	os.Stderr.Sync()
	metrics.FlushExporter()
}
<|endoftext|>