<commit_before>/*
Copyright 2019 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 guestbook

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/spf13/cobra"

	utilnet "k8s.io/apimachinery/pkg/util/net"
)

// CmdGuestbook is used by agnhost Cobra.
var CmdGuestbook = &cobra.Command{
	Use:   "guestbook",
	Short: "Creates a HTTP server with various endpoints representing a guestbook app",
	Long: `Starts a HTTP server on the given --http-port (default: 80), serving various endpoints representing a guestbook app. The endpoints and their purpose are:

- /register: A guestbook slave will subscribe to a master, to its given --slaveof endpoint. The master will then push any updates it receives to its registered slaves through the --backend-port.
- /get: Returns '{"data": value}', where the value is the stored value for the given key if non-empty, or the entire store.
- /set: Will set the given key-value pair in its own store and propagate it to its slaves, if any. Will return '{"data": "Updated"}' to the caller on success.
- /guestbook: Will proxy the request to agnhost-master if the given cmd is 'set', or agnhost-slave if the given cmd is 'get'.`,
	Args: cobra.MaximumNArgs(0),
	Run:  main,
}

var (
	httpPort    string
	backendPort string
	slaveOf     string
	slaves      []string
	store       map[string]interface{}
)

const (
	timeout = time.Duration(15) * time.Second
	sleep   = time.Duration(1) * time.Second
)

func init() {
	CmdGuestbook.Flags().StringVar(&httpPort, "http-port", "80", "HTTP Listen Port")
	CmdGuestbook.Flags().StringVar(&backendPort, "backend-port", "6379", "Backend's HTTP Listen Port")
	CmdGuestbook.Flags().StringVar(&slaveOf, "slaveof", "", "The host's name to register to")
	store = make(map[string]interface{})
}

func main(cmd *cobra.Command, args []string) {
	go registerNode(slaveOf, backendPort)
	startHTTPServer(httpPort)
}

func registerNode(registerTo, port string) {
	if registerTo == "" {
		return
	}

	hostPort := net.JoinHostPort(registerTo, backendPort)

	request := fmt.Sprintf("register?host=%s", getIP(hostPort).String())
	log.Printf("Registering to master: %s/%s", hostPort, request)
	start := time.Now()
	for time.Since(start) < timeout {
		_, err := net.ResolveTCPAddr("tcp", hostPort)
		if err != nil {
			log.Printf("--slaveof param and/or --backend-port param are invalid. %v. Retrying in 1 second.", err)
			time.Sleep(sleep)
			continue
		}

		response, err := dialHTTP(request, hostPort)
		if err != nil {
			log.Printf("encountered error while registering to master: %v. Retrying in 1 second.", err)
			time.Sleep(sleep)
			continue
		}

		responseJSON := make(map[string]interface{})
		err = json.Unmarshal([]byte(response), &responseJSON)
		if err != nil {
			log.Fatalf("Error while unmarshaling master's response: %v", err)
		}

		var ok bool
		store, ok = responseJSON["data"].(map[string]interface{})
		if !ok {
			log.Fatalf("Could not cast responseJSON: %s", responseJSON["data"])
		}
		log.Printf("Registered to node: %s", registerTo)
		return
	}

	log.Fatal("Timed out while registering to master.")
}

func startHTTPServer(port string) {
	http.HandleFunc("/register", registerHandler)<commit_msg>Improve error messages in agnhost/guestbook<commit_after>/*
Copyright 2019 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 guestbook

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/spf13/cobra"

	utilnet "k8s.io/apimachinery/pkg/util/net"
)

// CmdGuestbook is used by agnhost Cobra.
var CmdGuestbook = &cobra.Command{
	Use:   "guestbook",
	Short: "Creates a HTTP server with various endpoints representing a guestbook app",
	Long: `Starts a HTTP server on the given --http-port (default: 80), serving various endpoints representing a guestbook app. The endpoints and their purpose are:

- /register: A guestbook slave will subscribe to a master, to its given --slaveof endpoint. The master will then push any updates it receives to its registered slaves through the --backend-port.
- /get: Returns '{"data": value}', where the value is the stored value for the given key if non-empty, or the entire store.
- /set: Will set the given key-value pair in its own store and propagate it to its slaves, if any. Will return '{"data": "Updated"}' to the caller on success.
- /guestbook: Will proxy the request to agnhost-master if the given cmd is 'set', or agnhost-slave if the given cmd is 'get'.`,
	Args: cobra.MaximumNArgs(0),
	Run:  main,
}

var (
	httpPort    string
	backendPort string
	slaveOf     string
	slaves      []string
	store       map[string]interface{}
)

const (
	timeout = time.Duration(15) * time.Second
	sleep   = time.Duration(1) * time.Second
)

func init() {
	CmdGuestbook.Flags().StringVar(&httpPort, "http-port", "80", "HTTP Listen Port")
	CmdGuestbook.Flags().StringVar(&backendPort, "backend-port", "6379", "Backend's HTTP Listen Port")
	CmdGuestbook.Flags().StringVar(&slaveOf, "slaveof", "", "The host's name to register to")
	store = make(map[string]interface{})
}

func main(cmd *cobra.Command, args []string) {
	go registerNode(slaveOf, backendPort)
	startHTTPServer(httpPort)
}

func registerNode(registerTo, port string) {
	if registerTo == "" {
		return
	}

	hostPort := net.JoinHostPort(registerTo, backendPort)

	request := fmt.Sprintf("register?host=%s", getIP(hostPort).String())
	log.Printf("Registering to master: %s/%s", hostPort, request)
	start := time.Now()
	for time.Since(start) < timeout {
		_, err := net.ResolveTCPAddr("tcp", hostPort)
		if err != nil {
			log.Printf("unable to resolve %s, --slaveof param and/or --backend-port param are invalid: %v. Retrying in %s.", hostPort, err, sleep)
			time.Sleep(sleep)
			continue
		}

		response, err := dialHTTP(request, hostPort)
		if err != nil {
			log.Printf("encountered error while registering to master: %v. Retrying in %s.", err, sleep)
			time.Sleep(sleep)
			continue
		}

		responseJSON := make(map[string]interface{})
		err = json.Unmarshal([]byte(response), &responseJSON)
		if err != nil {
			log.Fatalf("Error while unmarshaling master's response: %v", err)
		}

		var ok bool
		store, ok = responseJSON["data"].(map[string]interface{})
		if !ok {
			log.Fatalf("Could not cast responseJSON: %s", responseJSON["data"])
		}
		log.Printf("Registered to node: %s", registerTo)
		return
	}

	log.Fatal("Timed out while registering to master.")
}

func startHTTPServer(port string) {
	http.HandleFunc("/register", registerHandler)
{'fraction_non_alphanumeric': 0.11954509389050516, 'fraction_numerical': 0.006347527109230362, 'mean_word_length': 4.2447988904299585, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6190918', 'n_tokens_mistral': 2493, 'n_tokens_neox': 2356, 'n_words': 836}