<commit_before>// Copyright 2015 CoreOS, Inc.
//
// 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.

// The azure provider fetches a configuration from the Azure OVF DVD.

package azure

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	"github.com/coreos/ignition/v2/config/v3_4_experimental/types"
	"github.com/coreos/ignition/v2/internal/distro"
	execUtil "github.com/coreos/ignition/v2/internal/exec/util"
	"github.com/coreos/ignition/v2/internal/log"
	"github.com/coreos/ignition/v2/internal/providers/util"
	"github.com/coreos/ignition/v2/internal/resource"

	"github.com/coreos/vcontext/report"
	"golang.org/x/sys/unix"
)

const (
	configDeviceID = "ata-Virtual_CD"
	configPath     = "/CustomData.bin"
)

// These constants come from <cdrom.h>.
const (
	CDROM_DRIVE_STATUS = 0x5326
)

// These constants come from <cdrom.h>.
const (
	CDS_NO_INFO = iota
	CDS_NO_DISC
	CDS_TRAY_OPEN
	CDS_DRIVE_NOT_READY
	CDS_DISC_OK
)

// Azure uses a UDF volume for the OVF configuration.
const (
	CDS_FSTYPE_UDF = "udf"
)

// FetchConfig wraps FetchOvfDevice to implement the platform.NewFetcher interface.
func FetchConfig(f *resource.Fetcher) (types.Config, report.Report, error) {
	return FetchFromOvfDevice(f, []string{CDS_FSTYPE_UDF})
}

// FetchFromOvfDevice has the return signature of platform.NewFetcher. It is
// wrapped by this and AzureStack packages.
func FetchFromOvfDevice(f *resource.Fetcher, ovfFsTypes []string) (types.Config, report.Report, error) {
	devicePath := filepath.Join(distro.DiskByIDDir(), configDeviceID)

	logger := f.Logger
	logger.Debug("waiting for config DVD...")
	waitForCdrom(logger, devicePath)

	fsType, err := checkOvfFsType(logger, devicePath, ovfFsTypes)
	if err != nil {
		return types.Config{}, report.Report{}, err
	}

	mnt, err := ioutil.TempDir("", "ignition-azure")
	if err != nil {
		return types.Config{}, report.Report{}, fmt.Errorf("failed to create temp directory: %v", err)
	}
	defer os.Remove(mnt)

	logger.Debug("mounting config device")
	if err := logger.LogOp(
		func() error { return unix.Mount(devicePath, mnt, fsType, unix.MS_RDONLY, "") },
		"mounting %q at %q", devicePath, mnt,
	); err != nil {
		return types.Config{}, report.Report{}, fmt.Errorf("failed to mount device %q at %q: %v", devicePath, mnt, err)
	}
	defer func() {
		_ = logger.LogOp(
			func() error { return unix.Unmount(mnt, 0) },
			"unmounting %q at %q", devicePath, mnt,
		)
	}()

	logger.Debug("reading config")
	rawConfig, err := ioutil.ReadFile(filepath.Join(mnt, configPath))
	if err != nil && !os.IsNotExist(err) {
		return types.Config{}, report.Report{}, fmt.Errorf("failed to read config: %v", err)
	}

	return util.ParseConfig(logger, rawConfig)
}

func waitForCdrom(logger *log.Logger, devicePath string) {
	for !isCdromPresent(logger, devicePath) {
		time.Sleep(time.Second)
	}
}

func isCdromPresent(logger *log.Logger, devicePath string) bool {
	logger.Debug("opening config device")
	device, err := os.Open(devicePath)
	if err != nil {
		logger.Info("failed to open config device: %v", err)
		return false
	}
	defer device.Close()

	logger.Debug("getting drive status")
	status, _, errno := unix.Syscall(
		unix.SYS_IOCTL,
		uintptr(device.Fd()),
		uintptr(CDROM_DRIVE_STATUS),
		uintptr(0),
	)

	switch status {
	case CDS_NO_INFO:
		logger.Info("drive status: no info")
	case CDS_NO_DISC:
		logger.Info("drive status: no disc")
	case CDS_TRAY_OPEN:
		logger.Info("drive status: open")
	case CDS_DRIVE_NOT_READY:
		logger.Info("drive status: not ready")
	case CDS_DISC_OK:
		logger.Info("drive status: OK")
	default:
		logger.Err("failed to get drive status: %s", errno.Error())
	}

	return (status == CDS_DISC_OK)
}

func checkOvfFsType(logger *log.Logger, devicePath string, fsTypes []string) (string, error) {
	fs, err := execUtil.GetFilesystemInfo(devicePath, false)
	if err != nil {
		return fs.Type, fmt.Errorf("failed to detect filesystem on ovf device %q: %v", devicePath, err)
	}
	for _, f := range fsTypes {
		if f == fs.Type {
			return fs.Type, nil
		}
	}
	return fs.Type, fmt.Errorf("filesystem %q is not a supported ovf device", fs.Type)
}
<commit_msg>providers/azure: add support for azure gen2 VMs<commit_after>// Copyright 2015 CoreOS, Inc.
//
// 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.

// The azure provider fetches a configuration from the Azure OVF DVD.

package azure

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	"github.com/coreos/ignition/v2/config/v3_4_experimental/types"
	execUtil "github.com/coreos/ignition/v2/internal/exec/util"
	"github.com/coreos/ignition/v2/internal/log"
	"github.com/coreos/ignition/v2/internal/providers/util"
	"github.com/coreos/ignition/v2/internal/resource"

	"github.com/coreos/vcontext/report"
	"golang.org/x/sys/unix"
)

const (
	configPath = "/CustomData.bin"
)

// These constants come from <cdrom.h>.
const (
	CDROM_DRIVE_STATUS = 0x5326
)

// These constants come from <cdrom.h>.
const (
	CDS_NO_INFO = iota
	CDS_NO_DISC
	CDS_TRAY_OPEN
	CDS_DRIVE_NOT_READY
	CDS_DISC_OK
)

// Azure uses a UDF volume for the OVF configuration.
const (
	CDS_FSTYPE_UDF = "udf"
)

// FetchConfig wraps FetchOvfDevice to implement the platform.NewFetcher interface.
func FetchConfig(f *resource.Fetcher) (types.Config, report.Report, error) {
	return FetchFromOvfDevice(f, []string{CDS_FSTYPE_UDF})
}

// FetchFromOvfDevice has the return signature of platform.NewFetcher. It is
// wrapped by this and AzureStack packages.
func FetchFromOvfDevice(f *resource.Fetcher, ovfFsTypes []string) (types.Config, report.Report, error) {
	logger := f.Logger
	checkedDevices := make(map[string]struct{})
	for {
		for _, ovfFsType := range ovfFsTypes {
			devices, err := execUtil.GetBlockDevices(ovfFsType)
			if err != nil {
				return types.Config{}, report.Report{}, fmt.Errorf("failed to retrieve block devices with FSTYPE=%q: %v", ovfFsType, err)
			}
			for _, dev := range devices {
				_, checked := checkedDevices[dev]
				// verify that this is a CD-ROM drive. This helps
				// to avoid reading data from an arbitrary block
				// device attached to the VM by the user.
				if !checked && isCdromPresent(logger, dev) {
					rawConfig, err := getRawConfig(f, dev, ovfFsType)
					if err != nil {
						logger.Debug("failed to retrieve config from device %q: %v", dev, err)
					} else {
						return util.ParseConfig(logger, rawConfig)
					}
				}
				checkedDevices[dev] = struct{}{}
			}
		}
		// wait for the actual config drive to appear
		// if it's not shown up yet
		time.Sleep(time.Second)
	}
}

// getRawConfig returns the config by mounting the given block device
func getRawConfig(f *resource.Fetcher, devicePath string, fstype string) ([]byte, error) {
	logger := f.Logger
	mnt, err := ioutil.TempDir("", "ignition-azure")
	if err != nil {
		return nil, fmt.Errorf("failed to create temp directory: %v", err)
	}
	defer os.Remove(mnt)

	logger.Debug("mounting config device")
	if err := logger.LogOp(
		func() error { return unix.Mount(devicePath, mnt, fstype, unix.MS_RDONLY, "") },
		"mounting %q at %q", devicePath, mnt,
	); err != nil {
		return nil, fmt.Errorf("failed to mount device %q at %q: %v", devicePath, mnt, err)
	}
	defer func() {
		_ = logger.LogOp(
			func() error { return unix.Unmount(mnt, 0) },
			"unmounting %q at %q", devicePath, mnt,
		)
	}()

	// detect the config drive by looking for a file which is always present
	logger.Debug("checking for config drive")
	if _, err := os.Stat(filepath.Join(mnt, "ovf-env.xml")); err != nil {
		return nil, fmt.Errorf("device %q does not appear to be a config drive: %v", devicePath, err)
	}

	logger.Debug("reading config")
	rawConfig, err := ioutil.ReadFile(filepath.Join(mnt, configPath))
	if err != nil && !os.IsNotExist(err) {
		return nil, fmt.Errorf("failed to read config from device %q: %v", devicePath, err)
	}
	return rawConfig, nil
}

// isCdromPresent verifies if the given config drive is CD-ROM
func isCdromPresent(logger *log.Logger, devicePath string) bool {
	logger.Debug("opening config device: %q", devicePath)
	device, err := os.Open(devicePath)
	if err != nil {
		logger.Info("failed to open config device: %v", err)
		return false
	}
	defer device.Close()

	logger.Debug("getting drive status for %q", devicePath)
	status, _, errno := unix.Syscall(
		unix.SYS_IOCTL,
		uintptr(device.Fd()),
		uintptr(CDROM_DRIVE_STATUS),
		uintptr(0),
	)

	switch status {
	case CDS_NO_INFO:
		logger.Info("drive status: no info")
	case CDS_NO_DISC:
		logger.Info("drive status: no disc")
	case CDS_TRAY_OPEN:
		logger.Info("drive status: open")
	case CDS_DRIVE_NOT_READY:
		logger.Info("drive status: not ready")
	case CDS_DISC_OK:
		logger.Info("drive status: OK")
	default:
		logger.Err("failed to get drive status: %s", errno.Error())
	}

	return (status == CDS_DISC_OK)
}
<|endoftext|>


<commit_before>package vaulted

import (
	"crypto/sha512"
	"errors"
	"fmt"
	"sort"
)

var (
	// SessionCacheVersion indicates the current version of the cache format.
	//
	// Any cache loaded that does not match this version is ignored. This
	// causes all caches written for previous versions to be invalidated.
	SessionCacheVersion = "3"
)

var (
	// ErrVaultSessionNotFound occurs when attempting to locate a vault session
	// in a SessionCache that isn't present.
	ErrVaultSessionNotFound = errors.New("Vault session not found")
)

// SessionCache stores sessions keyed based on the contents of the vault that
// spawned the session.
//
// See VaultSessionCacheKey for details on how the key is generated.
type SessionCache struct {
	SessionCacheVersion string              `json:"version"`
	Sessions            map[string]*Session `json:"sessions"`
}

// GetVaultSession retrieves a copy of a session in the cache.
//
// The retrieved session is keyed using the contents of the provided vault.
func (sc *SessionCache) GetVaultSession(vault *Vault) (*Session, error) {
	sessionKey := VaultSessionCacheKey(vault)
	if session, exists := sc.Sessions[sessionKey]; exists {
		return session.Clone(), nil
	}

	return nil, ErrVaultSessionNotFound
}

// PutVaultSession stores a copy of a session in the cache.
//
// The stored session is keyed using the contents of the provided vault.
func (sc *SessionCache) PutVaultSession(vault *Vault, session *Session) {
	if sc.Sessions == nil {
		sc.Sessions = make(map[string]*Session)
	}

	sessionKey := VaultSessionCacheKey(vault)
	sc.Sessions[sessionKey] = session.Clone()
}

// RemoveExpiredSessions removes sessions from the cache that have expired.
func (sc *SessionCache) RemoveExpiredSessions() {
	for key, session := range sc.Sessions {
		if session.Expired(NoTolerance) {
			delete(sc.Sessions, key)
		}
	}
}

// VaultSessionCacheKey computes a stable key based on the contents of a vault.
//
// The computed key is intended to be used for things such as a session cache.
func VaultSessionCacheKey(vault *Vault) string {
	// gather all of the key attributes
	keyAttributes := map[string]string{}

	if vault.AWSKey != nil {
		keyAttributes["aws_key_id"] = vault.AWSKey.ID
		keyAttributes["aws_key_secret"] = vault.AWSKey.Secret
		if vault.AWSKey.Region != nil {
			keyAttributes["aws_key_region"] = *vault.AWSKey.Region
		}

		keyAttributes["aws_key_mfa"] = vault.AWSKey.MFA
		keyAttributes["aws_key_role"] = vault.AWSKey.Role

		if vault.AWSKey.ForgoTempCredGeneration {
			keyAttributes["aws_key_sts"] = "false"
		} else {
			keyAttributes["aws_key_sts"] = "true"
		}
	}

	for key, value := range vault.Vars {
		keyAttributes["vars_"+key] = value
	}

	for key, value := range vault.SSHKeys {
		keyAttributes["ssh_key_"+key] = value
	}

	// we cannot compare the actual generated key, so instead we just
	// want to confirm that if its existence matches the current vault
	if vault.SSHOptions != nil && vault.SSHOptions.GenerateRSAKey {
		keyAttributes["generated_key_exists"] = "true"
	} else {
		keyAttributes["generated_key_exists"] = "false"
	}

	// get a sorted list of the keys (that do not have blank values)
	var keys []string
	for key, value := range keyAttributes {
		if value != "" {
			keys = append(keys, key)
		}
	}
	sort.Strings(keys)

	// digest the keys and values in a stable order
	digest := sha512.New()
	for _, key := range keys {
		digest.Write([]byte(key))
		digest.Write([]byte("\r"))

		digest.Write([]byte(keyAttributes[key]))
		digest.Write([]byte("\n"))
	}

	sum := make([]byte, digest.Size())
	digest.Sum(sum[:0])
	return fmt.Sprintf("%02x", sum)
}
<commit_msg>invalidate cached session if ssh option change<commit_after>package vaulted

import (
	"crypto/sha512"
	"errors"
	"fmt"
	"sort"
	"strings"
)

var (
	// SessionCacheVersion indicates the current version of the cache format.
	//
	// Any cache loaded that does not match this version is ignored. This
	// causes all caches written for previous versions to be invalidated.
	SessionCacheVersion = "3"
)

var (
	// ErrVaultSessionNotFound occurs when attempting to locate a vault session
	// in a SessionCache that isn't present.
	ErrVaultSessionNotFound = errors.New("Vault session not found")
)

// SessionCache stores sessions keyed based on the contents of the vault that
// spawned the session.
//
// See VaultSessionCacheKey for details on how the key is generated.
type SessionCache struct {
	SessionCacheVersion string              `json:"version"`
	Sessions            map[string]*Session `json:"sessions"`
}

// GetVaultSession retrieves a copy of a session in the cache.
//
// The retrieved session is keyed using the contents of the provided vault.
func (sc *SessionCache) GetVaultSession(vault *Vault) (*Session, error) {
	sessionKey := VaultSessionCacheKey(vault)
	if session, exists := sc.Sessions[sessionKey]; exists {
		return session.Clone(), nil
	}

	return nil, ErrVaultSessionNotFound
}

// PutVaultSession stores a copy of a session in the cache.
//
// The stored session is keyed using the contents of the provided vault.
func (sc *SessionCache) PutVaultSession(vault *Vault, session *Session) {
	if sc.Sessions == nil {
		sc.Sessions = make(map[string]*Session)
	}

	sessionKey := VaultSessionCacheKey(vault)
	sc.Sessions[sessionKey] = session.Clone()
}

// RemoveExpiredSessions removes sessions from the cache that have expired.
func (sc *SessionCache) RemoveExpiredSessions() {
	for key, session := range sc.Sessions {
		if session.Expired(NoTolerance) {
			delete(sc.Sessions, key)
		}
	}
}

// VaultSessionCacheKey computes a stable key based on the contents of a vault.
//
// The computed key is intended to be used for things such as a session cache.
func VaultSessionCacheKey(vault *Vault) string {
	// gather all of the key attributes
	keyAttributes := map[string]string{}

	if vault.AWSKey != nil {
		keyAttributes["aws_key_id"] = vault.AWSKey.ID
		keyAttributes["aws_key_secret"] = vault.AWSKey.Secret
		if vault.AWSKey.Region != nil {
			keyAttributes["aws_key_region"] = *vault.AWSKey.Region
		}

		keyAttributes["aws_key_mfa"] = vault.AWSKey.MFA
		keyAttributes["aws_key_role"] = vault.AWSKey.Role

		if vault.AWSKey.ForgoTempCredGeneration {
			keyAttributes["aws_key_sts"] = "false"
		} else {
			keyAttributes["aws_key_sts"] = "true"
		}
	}

	for key, value := range vault.Vars {
		keyAttributes["vars_"+key] = value
	}

	for key, value := range vault.SSHKeys {
		keyAttributes["ssh_key_"+key] = value
	}

	if vault.SSHOptions != nil {
		if vault.SSHOptions.DisableProxy {
			keyAttributes["ssh_disable_proxy"] = "true"
		} else {
			keyAttributes["ssh_disable_proxy"] = "false"
		}

		keyAttributes["ssh_vault_signing_url"] = vault.SSHOptions.VaultSigningUrl
		keyAttributes["ssh_vault_signing_users"] = strings.Join(vault.SSHOptions.ValidPrincipals, ", ")

		// we cannot compare the actual generated key, so instead we just
		// want to confirm that if its existence matches the current vault
		if vault.SSHOptions.GenerateRSAKey {
			keyAttributes["ssh_generated_key_exists"] = "true"
		} else {
			keyAttributes["ssh_generated_key_exists"] = "false"
		}
	}

	// get a sorted list of the keys (that do not have blank values)
	var keys []string
	for key, value := range keyAttributes {
		if value != "" {
			keys = append(keys, key)
		}
	}
	sort.Strings(keys)

	// digest the keys and values in a stable order
	digest := sha512.New()
	for _, key := range keys {
		digest.Write([]byte(key))
		digest.Write([]byte("\r"))

		digest.Write([]byte(keyAttributes[key]))
		digest.Write([]byte("\n"))
	}

	sum := make([]byte, digest.Size())
	digest.Sum(sum[:0])
	return fmt.Sprintf("%02x", sum)
}
<|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.
*/

// Build the binary with `go build conformance.go`, then run the conformance binary on a node candidate.  If compiled
// on a non-linux machine, must be cross compiled for the host.
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"os/exec"
	"regexp"
	"strings"

	"errors"
	"os"

	"k8s.io/kubernetes/pkg/kubelet/cadvisor"
)

const success = "\033[0;32mSUCESS\033[0m"
const failed = "\033[0;31mFAILED\033[0m"
const notConfigured = "\033[0;34mNOT CONFIGURED\033[0m"
const skipped = "\033[0;34mSKIPPED\033[0m"

var checkFlag = flag.String(
	"check", "all", "what to check for conformance.  One or more of all,container-runtime,daemons,dns,firewall,kernel")

func init() {
	// Set this to false to undo util/logs.go settings it to true.  Prevents cadvisor log spam.
	// Remove this once util/logs.go stops setting the flag to true.
	flag.Set("logtostderr", "false")
}

// TODO: Should we write an e2e test for this?
func main() {
	flag.Parse()
	o := strings.Split(*checkFlag, ",")
	errs := check(o...)
	if len(errs) > 0 {
		os.Exit(1)
	} else {
		os.Exit(0)
	}
}

// check returns errors found while checking the provided components.  Will prevent errors to stdout.
func check(options ...string) []error {
	errs := []error{}
	for _, c := range options {
		switch c {
		case "all":
			errs = appendNotNil(errs, kernel())
			errs = appendNotNil(errs, containerRuntime())
			errs = appendNotNil(errs, daemons())
			errs = appendNotNil(errs, firewall())
			errs = appendNotNil(errs, dns())
		case "containerruntime":
			errs = appendNotNil(errs, containerRuntime())
		case "daemons":
			errs = appendNotNil(errs, daemons())
		case "dns":
			errs = appendNotNil(errs, dns())
		case "firewall":
			errs = appendNotNil(errs, firewall())
		case "kernel":
			errs = appendNotNil(errs, kernel())
		default:
			fmt.Printf("Unrecognized option %s\n", c)
			errs = append(errs, fmt.Errorf("Unrecognized option %s", c))
		}
	}
	return errs
}

const dockerVersionRegex = `1\.[7-9]\.[0-9]+`

// containerRuntime checks that a suitable container runtime is installed and recognized by cadvisor: docker 1.7-1.9
func containerRuntime() error {
	dockerRegex, err := regexp.Compile(dockerVersionRegex)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}

	// Setup cadvisor to check the container environment
	c, err := cadvisor.New(cadvisor.NewImageFsInfoProvider("docker", ""), "/var/lib/kubelet", []string{"/"}, false)
	if err != nil {
		return printError("Container Runtime Check: %s Could not start cadvisor %v", failed, err)
	}

	vi, err := c.VersionInfo()
	if err != nil {
		return printError("Container Runtime Check: %s Could not get VersionInfo %v", failed, err)
	}

	d := vi.DockerVersion
	if !dockerRegex.Match([]byte(d)) {
		return printError(
			"Container Runtime Check: %s Docker version %s does not matching %s.  You may need to run as root or the "+
				"user the kubelet will run under.", failed, d, dockerVersionRegex)
	}

	return printSuccess("Container Runtime Check: %s", success)
}

const kubeletClusterDNSRegexStr = `\/kubelet.*--cluster-dns=(\S+) `
const kubeletClusterDomainRegexStr = `\/kubelet.*--cluster-domain=(\S+)`

// dns checks that cluster dns has been properly configured and can resolve the kubernetes.default service
func dns() error {
	dnsRegex, err := regexp.Compile(kubeletClusterDNSRegexStr)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}
	domainRegex, err := regexp.Compile(kubeletClusterDomainRegexStr)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}

	h, err := net.LookupHost("kubernetes.default")
	if err == nil {
		return printSuccess("Dns Check (Optional): %s", success)
	}
	if len(h) > 0 {
		return printSuccess("Dns Check (Optional): %s", success)
	}

	kubecmd, err := exec.Command("ps", "aux").CombinedOutput()
	if err != nil {
		// Executing ps aux shouldn't have failed
		panic(err)
	}

	// look for the dns flag and parse the value
	dns := dnsRegex.FindStringSubmatch(string(kubecmd))
	if len(dns) < 2 {
		return printSuccess(
			"Dns Check (Optional): %s No hosts resolve to kubernetes.default.  kubelet will need to set "+
				"--cluster-dns and --cluster-domain when run", notConfigured)
	}

	// look for the domain flag and parse the value
	domain := domainRegex.FindStringSubmatch(string(kubecmd))
	if len(domain) < 2 {
		return printSuccess(
			"Dns Check (Optional): %s No hosts resolve to kubernetes.default.  kubelet will need to set "+
				"--cluster-dns and --cluster-domain when run", notConfigured)
	}

	// do a lookup with the flags the kubelet is running with
	nsArgs := []string{"-q=a", fmt.Sprintf("kubernetes.default.%s", domain[1]), dns[1]}
	if err = exec.Command("nslookup", nsArgs...).Run(); err != nil {
		// Mark this as failed since there was a clear intention to set it up, but it is done so improperly
		return printError(
			"Dns Check (Optional): %s No hosts resolve to kubernetes.default  kubelet found, but cannot resolve "+
				"kubernetes.default using nslookup %s error: %v", failed, strings.Join(nsArgs, " "), err)
	}

	// Can resolve kubernetes.default using the kubelete dns and domain values
	return printSuccess("Dns Check (Optional): %s", success)
}

const cmdlineCGroupMemory = `cgroup_enable=memory`

// kernel checks that the kernel has been configured correctly to support the required cgroup features
func kernel() error {
	cmdline, err := ioutil.ReadFile("/proc/cmdline")
	if err != nil {
		return printError("Kernel Command Line Check %s: Could not check /proc/cmdline", failed)
	}
	if !strings.Contains(string(cmdline), cmdlineCGroupMemory) {
		return printError("Kernel Command Line Check %s: cgroup_enable=memory not enabled in /proc/cmdline", failed)
	}
	return printSuccess("Kernel Command Line %s", success)
}

const iptablesInputRegexStr = `Chain INPUT \(policy DROP\)`
const iptablesForwardRegexStr = `Chain FORWARD \(policy DROP\)`

// firewall checks that iptables does not have common firewall rules setup that would disrupt traffic
func firewall() error {
	out, err := exec.Command("iptables", "-L", "INPUT").CombinedOutput()
	if err != nil {
		return printSuccess("Firewall IPTables Check %s: Could not run iptables", skipped)
	}
	inputRegex, err := regexp.Compile(iptablesInputRegexStr)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}
	if inputRegex.Match(out) {
		return printError("Firewall IPTables Check %s: Found INPUT rule matching %s", failed, iptablesInputRegexStr)
	}

	// Check GCE forward rules
	out, err = exec.Command("iptables", "-L", "FORWARD").CombinedOutput()
	if err != nil {
		return printSuccess("Firewall IPTables Check %s: Could not run iptables", skipped)
	}
	forwardRegex, err := regexp.Compile(iptablesForwardRegexStr)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}
	if forwardRegex.Match(out) {
		return printError("Firewall IPTables Check %s: Found FORWARD rule matching %s", failed, iptablesInputRegexStr)
	}

	return printSuccess("Firewall IPTables Check %s", success)
}

// daemons checks that the required node programs are running: kubelet, kube-proxy, and docker
func daemons() error {
	if exec.Command("pgrep", "-f", "kubelet").Run() != nil {
		return printError("Daemon Check %s: kubelet process not found", failed)
	}

	if exec.Command("pgrep", "-f", "kube-proxy").Run() != nil {
		return printError("Daemon Check %s: kube-proxy process not found", failed)
	}

	return printSuccess("Daemon Check %s", success)
}

// printError provides its arguments to print a format string to the console (newline terminated) and returns an
// error with the same string
func printError(s string, args ...interface{}) error {
	es := fmt.Sprintf(s, args...)
	fmt.Println(es)
	return errors.New(es)
}

// printSuccess provides its arguments to print a format string to the console (newline terminated) and returns nil
func printSuccess(s string, args ...interface{}) error {
	fmt.Println(fmt.Sprintf(s, args...))
	return nil
}

// appendNotNil appends err to errs iff err is not nil
func appendNotNil(errs []error, err error) []error {
	if err != nil {
		return append(errs, err)
	}
	return errs
}
<commit_msg>Update comment to not indicate check is run for docker daemon<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.
*/

// Build the binary with `go build conformance.go`, then run the conformance binary on a node candidate.  If compiled
// on a non-linux machine, must be cross compiled for the host.
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"os/exec"
	"regexp"
	"strings"

	"errors"
	"os"

	"k8s.io/kubernetes/pkg/kubelet/cadvisor"
)

const success = "\033[0;32mSUCESS\033[0m"
const failed = "\033[0;31mFAILED\033[0m"
const notConfigured = "\033[0;34mNOT CONFIGURED\033[0m"
const skipped = "\033[0;34mSKIPPED\033[0m"

var checkFlag = flag.String(
	"check", "all", "what to check for conformance.  One or more of all,container-runtime,daemons,dns,firewall,kernel")

func init() {
	// Set this to false to undo util/logs.go settings it to true.  Prevents cadvisor log spam.
	// Remove this once util/logs.go stops setting the flag to true.
	flag.Set("logtostderr", "false")
}

// TODO: Should we write an e2e test for this?
func main() {
	flag.Parse()
	o := strings.Split(*checkFlag, ",")
	errs := check(o...)
	if len(errs) > 0 {
		os.Exit(1)
	} else {
		os.Exit(0)
	}
}

// check returns errors found while checking the provided components.  Will prevent errors to stdout.
func check(options ...string) []error {
	errs := []error{}
	for _, c := range options {
		switch c {
		case "all":
			errs = appendNotNil(errs, kernel())
			errs = appendNotNil(errs, containerRuntime())
			errs = appendNotNil(errs, daemons())
			errs = appendNotNil(errs, firewall())
			errs = appendNotNil(errs, dns())
		case "containerruntime":
			errs = appendNotNil(errs, containerRuntime())
		case "daemons":
			errs = appendNotNil(errs, daemons())
		case "dns":
			errs = appendNotNil(errs, dns())
		case "firewall":
			errs = appendNotNil(errs, firewall())
		case "kernel":
			errs = appendNotNil(errs, kernel())
		default:
			fmt.Printf("Unrecognized option %s\n", c)
			errs = append(errs, fmt.Errorf("Unrecognized option %s", c))
		}
	}
	return errs
}

const dockerVersionRegex = `1\.[7-9]\.[0-9]+`

// containerRuntime checks that a suitable container runtime is installed and recognized by cadvisor: docker 1.7-1.9
func containerRuntime() error {
	dockerRegex, err := regexp.Compile(dockerVersionRegex)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}

	// Setup cadvisor to check the container environment
	c, err := cadvisor.New(cadvisor.NewImageFsInfoProvider("docker", ""), "/var/lib/kubelet", []string{"/"}, false)
	if err != nil {
		return printError("Container Runtime Check: %s Could not start cadvisor %v", failed, err)
	}

	vi, err := c.VersionInfo()
	if err != nil {
		return printError("Container Runtime Check: %s Could not get VersionInfo %v", failed, err)
	}

	d := vi.DockerVersion
	if !dockerRegex.Match([]byte(d)) {
		return printError(
			"Container Runtime Check: %s Docker version %s does not matching %s.  You may need to run as root or the "+
				"user the kubelet will run under.", failed, d, dockerVersionRegex)
	}

	return printSuccess("Container Runtime Check: %s", success)
}

const kubeletClusterDNSRegexStr = `\/kubelet.*--cluster-dns=(\S+) `
const kubeletClusterDomainRegexStr = `\/kubelet.*--cluster-domain=(\S+)`

// dns checks that cluster dns has been properly configured and can resolve the kubernetes.default service
func dns() error {
	dnsRegex, err := regexp.Compile(kubeletClusterDNSRegexStr)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}
	domainRegex, err := regexp.Compile(kubeletClusterDomainRegexStr)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}

	h, err := net.LookupHost("kubernetes.default")
	if err == nil {
		return printSuccess("Dns Check (Optional): %s", success)
	}
	if len(h) > 0 {
		return printSuccess("Dns Check (Optional): %s", success)
	}

	kubecmd, err := exec.Command("ps", "aux").CombinedOutput()
	if err != nil {
		// Executing ps aux shouldn't have failed
		panic(err)
	}

	// look for the dns flag and parse the value
	dns := dnsRegex.FindStringSubmatch(string(kubecmd))
	if len(dns) < 2 {
		return printSuccess(
			"Dns Check (Optional): %s No hosts resolve to kubernetes.default.  kubelet will need to set "+
				"--cluster-dns and --cluster-domain when run", notConfigured)
	}

	// look for the domain flag and parse the value
	domain := domainRegex.FindStringSubmatch(string(kubecmd))
	if len(domain) < 2 {
		return printSuccess(
			"Dns Check (Optional): %s No hosts resolve to kubernetes.default.  kubelet will need to set "+
				"--cluster-dns and --cluster-domain when run", notConfigured)
	}

	// do a lookup with the flags the kubelet is running with
	nsArgs := []string{"-q=a", fmt.Sprintf("kubernetes.default.%s", domain[1]), dns[1]}
	if err = exec.Command("nslookup", nsArgs...).Run(); err != nil {
		// Mark this as failed since there was a clear intention to set it up, but it is done so improperly
		return printError(
			"Dns Check (Optional): %s No hosts resolve to kubernetes.default  kubelet found, but cannot resolve "+
				"kubernetes.default using nslookup %s error: %v", failed, strings.Join(nsArgs, " "), err)
	}

	// Can resolve kubernetes.default using the kubelete dns and domain values
	return printSuccess("Dns Check (Optional): %s", success)
}

const cmdlineCGroupMemory = `cgroup_enable=memory`

// kernel checks that the kernel has been configured correctly to support the required cgroup features
func kernel() error {
	cmdline, err := ioutil.ReadFile("/proc/cmdline")
	if err != nil {
		return printError("Kernel Command Line Check %s: Could not check /proc/cmdline", failed)
	}
	if !strings.Contains(string(cmdline), cmdlineCGroupMemory) {
		return printError("Kernel Command Line Check %s: cgroup_enable=memory not enabled in /proc/cmdline", failed)
	}
	return printSuccess("Kernel Command Line %s", success)
}

const iptablesInputRegexStr = `Chain INPUT \(policy DROP\)`
const iptablesForwardRegexStr = `Chain FORWARD \(policy DROP\)`

// firewall checks that iptables does not have common firewall rules setup that would disrupt traffic
func firewall() error {
	out, err := exec.Command("iptables", "-L", "INPUT").CombinedOutput()
	if err != nil {
		return printSuccess("Firewall IPTables Check %s: Could not run iptables", skipped)
	}
	inputRegex, err := regexp.Compile(iptablesInputRegexStr)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}
	if inputRegex.Match(out) {
		return printError("Firewall IPTables Check %s: Found INPUT rule matching %s", failed, iptablesInputRegexStr)
	}

	// Check GCE forward rules
	out, err = exec.Command("iptables", "-L", "FORWARD").CombinedOutput()
	if err != nil {
		return printSuccess("Firewall IPTables Check %s: Could not run iptables", skipped)
	}
	forwardRegex, err := regexp.Compile(iptablesForwardRegexStr)
	if err != nil {
		// This should never happen and can only be fixed by changing the code
		panic(err)
	}
	if forwardRegex.Match(out) {
		return printError("Firewall IPTables Check %s: Found FORWARD rule matching %s", failed, iptablesInputRegexStr)
	}

	return printSuccess("Firewall IPTables Check %s", success)
}

// daemons checks that the required node programs are running: kubelet and kube-proxy
func daemons() error {
	if exec.Command("pgrep", "-f", "kubelet").Run() != nil {
		return printError("Daemon Check %s: kubelet process not found", failed)
	}

	if exec.Command("pgrep", "-f", "kube-proxy").Run() != nil {
		return printError("Daemon Check %s: kube-proxy process not found", failed)
	}

	return printSuccess("Daemon Check %s", success)
}

// printError provides its arguments to print a format string to the console (newline terminated) and returns an
// error with the same string
func printError(s string, args ...interface{}) error {
	es := fmt.Sprintf(s, args...)
	fmt.Println(es)
	return errors.New(es)
}

// printSuccess provides its arguments to print a format string to the console (newline terminated) and returns nil
func printSuccess(s string, args ...interface{}) error {
	fmt.Println(fmt.Sprintf(s, args...))
	return nil
}

// appendNotNil appends err to errs iff err is not nil
func appendNotNil(errs []error, err error) []error {
	if err != nil {
		return append(errs, err)
	}
	return errs
}
<|endoftext|>


<commit_before>/*
Copyright 2018 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 v1beta1

const (
	statusActive     = "Active"
	statusDeprecated = "Deprecated"
)

// GetName returns the class's name.
func (c *ClusterServiceClass) GetName() string {
	return c.Name
}

// GetName returns the class's name.
func (c *ServiceClass) GetName() string {
	return c.Name
}

// GetNamespace for cluster-scoped classes always returns "".
func (c *ClusterServiceClass) GetNamespace() string {
	return ""
}

// GetNamespace returns the class's namespace.
func (c *ServiceClass) GetNamespace() string {
	return c.Namespace
}

// GetExternalName returns the class's external name.
func (c *ClusterServiceClass) GetExternalName() string {
	return c.Spec.ExternalName
}

// GetExternalName returns the class's external name.
func (c *ServiceClass) GetExternalName() string {
	return c.Spec.ExternalName
}

// GetDescription returns the class description.
func (c *ClusterServiceClass) GetDescription() string {
	return c.Spec.Description
}

// GetDescription returns the class description.
func (c *ServiceClass) GetDescription() string {
	return c.Spec.Description
}

// GetSpec returns the spec for the class.
func (c *ServiceClass) GetSpec() CommonServiceClassSpec {
	return c.Spec.CommonServiceClassSpec
}

// GetSpec returns the spec for the class.
func (c *ClusterServiceClass) GetSpec() CommonServiceClassSpec {
	return c.Spec.CommonServiceClassSpec
}

// GetServiceBrokerName returns the name of the service broker for the class.
func (c *ServiceClass) GetServiceBrokerName() string {
	return c.Spec.ServiceBrokerName
}

// GetServiceBrokerName returns the name of the service broker for the class.
func (c *ClusterServiceClass) GetServiceBrokerName() string {
	return c.Spec.ClusterServiceBrokerName
}

// GetStatusText returns the sttaus of the class.
func (c *ServiceClass) GetStatusText() string {
	return c.Status.GetStatusText()
}

// GetStatusText returns the sttaus of the class.
func (c *ClusterServiceClass) GetStatusText() string {
	return c.Status.GetStatusText()
}

// GetStatusText returns the status based on the CommonServiceClassStatus.
func (c *CommonServiceClassStatus) GetStatusText() string {
	if c.RemovedFromBrokerCatalog {
		return statusDeprecated
	}
	return statusActive
}
<commit_msg>fix typo in class.go (#2423)<commit_after>/*
Copyright 2018 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 v1beta1

const (
	statusActive     = "Active"
	statusDeprecated = "Deprecated"
)

// GetName returns the class's name.
func (c *ClusterServiceClass) GetName() string {
	return c.Name
}

// GetName returns the class's name.
func (c *ServiceClass) GetName() string {
	return c.Name
}

// GetNamespace for cluster-scoped classes always returns "".
func (c *ClusterServiceClass) GetNamespace() string {
	return ""
}

// GetNamespace returns the class's namespace.
func (c *ServiceClass) GetNamespace() string {
	return c.Namespace
}

// GetExternalName returns the class's external name.
func (c *ClusterServiceClass) GetExternalName() string {
	return c.Spec.ExternalName
}

// GetExternalName returns the class's external name.
func (c *ServiceClass) GetExternalName() string {
	return c.Spec.ExternalName
}

// GetDescription returns the class description.
func (c *ClusterServiceClass) GetDescription() string {
	return c.Spec.Description
}

// GetDescription returns the class description.
func (c *ServiceClass) GetDescription() string {
	return c.Spec.Description
}

// GetSpec returns the spec for the class.
func (c *ServiceClass) GetSpec() CommonServiceClassSpec {
	return c.Spec.CommonServiceClassSpec
}

// GetSpec returns the spec for the class.
func (c *ClusterServiceClass) GetSpec() CommonServiceClassSpec {
	return c.Spec.CommonServiceClassSpec
}

// GetServiceBrokerName returns the name of the service broker for the class.
func (c *ServiceClass) GetServiceBrokerName() string {
	return c.Spec.ServiceBrokerName
}

// GetServiceBrokerName returns the name of the service broker for the class.
func (c *ClusterServiceClass) GetServiceBrokerName() string {
	return c.Spec.ClusterServiceBrokerName
}

// GetStatusText returns the status of the class.
func (c *ServiceClass) GetStatusText() string {
	return c.Status.GetStatusText()
}

// GetStatusText returns the status of the class.
func (c *ClusterServiceClass) GetStatusText() string {
	return c.Status.GetStatusText()
}

// GetStatusText returns the status based on the CommonServiceClassStatus.
func (c *CommonServiceClassStatus) GetStatusText() string {
	if c.RemovedFromBrokerCatalog {
		return statusDeprecated
	}
	return statusActive
}
<|endoftext|>


<commit_before>package v2

import (
	"context"
	"flag"
	"fmt"
	"math/rand"
	"net/http"
	"sync"
	"time"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
	"github.com/grafana/dskit/flagext"
	"github.com/grafana/dskit/grpcclient"
	"github.com/grafana/dskit/netutil"
	"github.com/grafana/dskit/ring"
	"github.com/grafana/dskit/services"
	"github.com/opentracing/opentracing-go"
	"github.com/pkg/errors"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/weaveworks/common/httpgrpc"
	"go.uber.org/atomic"

	"github.com/grafana/dskit/tenant"

	"github.com/grafana/loki/pkg/lokifrontend/frontend/v2/frontendv2pb"
	"github.com/grafana/loki/pkg/querier/stats"
	lokigrpc "github.com/grafana/loki/pkg/util/httpgrpc"
	util_log "github.com/grafana/loki/pkg/util/log"
)

// Config for a Frontend.
type Config struct {
	SchedulerAddress  string            `yaml:"scheduler_address"`
	DNSLookupPeriod   time.Duration     `yaml:"scheduler_dns_lookup_period"`
	WorkerConcurrency int               `yaml:"scheduler_worker_concurrency"`
	GRPCClientConfig  grpcclient.Config `yaml:"grpc_client_config"`

	// Used to find local IP address, that is sent to scheduler and querier-worker.
	InfNames []string `yaml:"instance_interface_names"`

	// If set, address is not computed from interfaces.
	Addr string `yaml:"address" doc:"hidden"`
	Port int    `doc:"hidden"`
}

func (cfg *Config) RegisterFlags(f *flag.FlagSet) {
	f.StringVar(&cfg.SchedulerAddress, "frontend.scheduler-address", "", "DNS hostname used for finding query-schedulers.")
	f.DurationVar(&cfg.DNSLookupPeriod, "frontend.scheduler-dns-lookup-period", 10*time.Second, "How often to resolve the scheduler-address, in order to look for new query-scheduler instances. Also used to determine how often to poll the scheduler-ring for addresses if the scheduler-ring is configured.")
	f.IntVar(&cfg.WorkerConcurrency, "frontend.scheduler-worker-concurrency", 5, "Number of concurrent workers forwarding queries to single query-scheduler.")

	cfg.InfNames = netutil.PrivateNetworkInterfacesWithFallback([]string{"eth0", "en0"}, util_log.Logger)
	f.Var((*flagext.StringSlice)(&cfg.InfNames), "frontend.instance-interface-names", "Name of network interface to read address from. This address is sent to query-scheduler and querier, which uses it to send the query response back to query-frontend.")
	f.StringVar(&cfg.Addr, "frontend.instance-addr", "", "IP address to advertise to querier (via scheduler) (resolved via interfaces by default).")
	f.IntVar(&cfg.Port, "frontend.instance-port", 0, "Port to advertise to querier (via scheduler) (defaults to server.grpc-listen-port).")

	cfg.GRPCClientConfig.RegisterFlagsWithPrefix("frontend.grpc-client-config", f)
}

// Frontend implements GrpcRoundTripper. It queues HTTP requests,
// dispatches them to backends via gRPC, and handles retries for requests which failed.
type Frontend struct {
	services.Service

	cfg Config
	log log.Logger

	lastQueryID atomic.Uint64

	// frontend workers will read from this channel, and send request to scheduler.
	requestsCh chan *frontendRequest

	schedulerWorkers *frontendSchedulerWorkers
	requests         *requestsInProgress
}

type frontendRequest struct {
	queryID      uint64
	request      *httpgrpc.HTTPRequest
	userID       string
	statsEnabled bool

	cancel context.CancelFunc

	enqueue  chan enqueueResult
	response chan *frontendv2pb.QueryResultRequest
}

type enqueueStatus int

const (
	// Sent to scheduler successfully, and frontend should wait for response now.
	waitForResponse enqueueStatus = iota

	// Failed to forward request to scheduler, frontend will try again.
	failed
)

type enqueueResult struct {
	status enqueueStatus

	cancelCh chan<- uint64 // Channel that can be used for request cancellation. If nil, cancellation is not possible.
}

// NewFrontend creates a new frontend.
func NewFrontend(cfg Config, ring ring.ReadRing, log log.Logger, reg prometheus.Registerer) (*Frontend, error) {
	requestsCh := make(chan *frontendRequest)

	schedulerWorkers, err := newFrontendSchedulerWorkers(cfg, fmt.Sprintf("%s:%d", cfg.Addr, cfg.Port), ring, requestsCh, log)
	if err != nil {
		return nil, err
	}

	f := &Frontend{
		cfg:              cfg,
		log:              log,
		requestsCh:       requestsCh,
		schedulerWorkers: schedulerWorkers,
		requests:         newRequestsInProgress(),
	}
	// Randomize to avoid getting responses from queries sent before restart, which could lead to mixing results
	// between different queries. Note that frontend verifies the user, so it cannot leak results between tenants.
	// This isn't perfect, but better than nothing.
	f.lastQueryID.Store(rand.Uint64())

	promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
		Name: "cortex_query_frontend_queries_in_progress",
		Help: "Number of queries in progress handled by this frontend.",
	}, func() float64 {
		return float64(f.requests.count())
	})

	promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
		Name: "cortex_query_frontend_connected_schedulers",
		Help: "Number of schedulers this frontend is connected to.",
	}, func() float64 {
		return float64(f.schedulerWorkers.getWorkersCount())
	})

	f.Service = services.NewIdleService(f.starting, f.stopping)
	return f, nil
}

func (f *Frontend) starting(ctx context.Context) error {
	return errors.Wrap(services.StartAndAwaitRunning(ctx, f.schedulerWorkers), "failed to start frontend scheduler workers")
}

func (f *Frontend) stopping(_ error) error {
	return errors.Wrap(services.StopAndAwaitTerminated(context.Background(), f.schedulerWorkers), "failed to stop frontend scheduler workers")
}

// RoundTripGRPC round trips a proto (instead of a HTTP request).
func (f *Frontend) RoundTripGRPC(ctx context.Context, req *httpgrpc.HTTPRequest) (*httpgrpc.HTTPResponse, error) {
	if s := f.State(); s != services.Running {
		return nil, fmt.Errorf("frontend not running: %v", s)
	}

	tenantIDs, err := tenant.TenantIDs(ctx)
	if err != nil {
		return nil, err
	}
	userID := tenant.JoinTenantIDs(tenantIDs)

	// Propagate trace context in gRPC too - this will be ignored if using HTTP.
	tracer, span := opentracing.GlobalTracer(), opentracing.SpanFromContext(ctx)
	if tracer != nil && span != nil {
		carrier := (*lokigrpc.HeadersCarrier)(req)
		if err := tracer.Inject(span.Context(), opentracing.HTTPHeaders, carrier); err != nil {
			return nil, err
		}
	}

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	freq := &frontendRequest{
		queryID:      f.lastQueryID.Inc(),
		request:      req,
		userID:       userID,
		statsEnabled: stats.IsEnabled(ctx),

		cancel: cancel,

		// Buffer of 1 to ensure response or error can be written to the channel
		// even if this goroutine goes away due to client context cancellation.
		enqueue:  make(chan enqueueResult, 1),
		response: make(chan *frontendv2pb.QueryResultRequest, 1),
	}

	f.requests.put(freq)
	defer f.requests.delete(freq.queryID)

	retries := f.cfg.WorkerConcurrency + 1 // To make sure we hit at least two different schedulers.

enqueueAgain:
	var cancelCh chan<- uint64
	select {
	case <-ctx.Done():
		return nil, ctx.Err()

	case f.requestsCh <- freq:
		// Enqueued, let's wait for response.
		enqRes := <-freq.enqueue

		if enqRes.status == waitForResponse {
			cancelCh = enqRes.cancelCh
			break // go wait for response.
		} else if enqRes.status == failed {
			retries--
			if retries > 0 {
				goto enqueueAgain
			}
		}

		return nil, httpgrpc.Errorf(http.StatusInternalServerError, "failed to enqueue request")
	}

	select {
	case <-ctx.Done():
		if cancelCh != nil {
			select {
			case cancelCh <- freq.queryID:
				// cancellation sent.
			default:
				// failed to cancel, ignore.
				level.Warn(f.log).Log("msg", "failed to send cancellation request to scheduler, queue full")
			}
		}
		return nil, ctx.Err()

	case resp := <-freq.response:
		if stats.ShouldTrackHTTPGRPCResponse(resp.HttpResponse) {
			stats := stats.FromContext(ctx)
			stats.Merge(resp.Stats) // Safe if stats is nil.
		}

		return resp.HttpResponse, nil
	}
}

func (f *Frontend) QueryResult(ctx context.Context, qrReq *frontendv2pb.QueryResultRequest) (*frontendv2pb.QueryResultResponse, error) {
	tenantIDs, err := tenant.TenantIDs(ctx)
	if err != nil {
		return nil, err
	}
	userID := tenant.JoinTenantIDs(tenantIDs)

	req := f.requests.get(qrReq.QueryID)
	// It is possible that some old response belonging to different user was received, if frontend has restarted.
	// To avoid leaking query results between users, we verify the user here.
	// To avoid mixing results from different queries, we randomize queryID counter on start.
	if req != nil && req.userID == userID {
		select {
		case req.response <- qrReq:
			// Should always be possible, unless QueryResult is called multiple times with the same queryID.
		default:
			level.Warn(f.log).Log("msg", "failed to write query result to the response channel", "queryID", qrReq.QueryID, "user", userID)
		}
	}

	return &frontendv2pb.QueryResultResponse{}, nil
}

// CheckReady determines if the query frontend is ready.  Function parameters/return
// chosen to match the same method in the ingester
func (f *Frontend) CheckReady(_ context.Context) error {
	workers := f.schedulerWorkers.getWorkersCount()

	// If frontend is connected to at least one scheduler, we are ready.
	if workers > 0 {
		return nil
	}

	msg := fmt.Sprintf("not ready: number of schedulers this worker is connected to is %d", workers)
	level.Info(f.log).Log("msg", msg)
	return errors.New(msg)
}

type requestsInProgress struct {
	mu       sync.Mutex
	requests map[uint64]*frontendRequest
}

func newRequestsInProgress() *requestsInProgress {
	return &requestsInProgress{
		requests: map[uint64]*frontendRequest{},
	}
}

func (r *requestsInProgress) count() int {
	r.mu.Lock()
	defer r.mu.Unlock()

	return len(r.requests)
}

func (r *requestsInProgress) put(req *frontendRequest) {
	r.mu.Lock()
	defer r.mu.Unlock()

	r.requests[req.queryID] = req
}

func (r *requestsInProgress) delete(queryID uint64) {
	r.mu.Lock()
	defer r.mu.Unlock()

	delete(r.requests, queryID)
}

func (r *requestsInProgress) get(queryID uint64) *frontendRequest {
	r.mu.Lock()
	defer r.mu.Unlock()

	return r.requests[queryID]
}
<commit_msg>stripes frontend requests in progress (#6679)<commit_after>package v2

import (
	"context"
	"flag"
	"fmt"
	"math/rand"
	"net/http"
	"sync"
	"time"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
	"github.com/grafana/dskit/flagext"
	"github.com/grafana/dskit/grpcclient"
	"github.com/grafana/dskit/netutil"
	"github.com/grafana/dskit/ring"
	"github.com/grafana/dskit/services"
	"github.com/opentracing/opentracing-go"
	"github.com/pkg/errors"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/weaveworks/common/httpgrpc"
	"go.uber.org/atomic"

	"github.com/grafana/dskit/tenant"

	"github.com/grafana/loki/pkg/lokifrontend/frontend/v2/frontendv2pb"
	"github.com/grafana/loki/pkg/querier/stats"
	lokigrpc "github.com/grafana/loki/pkg/util/httpgrpc"
	util_log "github.com/grafana/loki/pkg/util/log"
)

// Config for a Frontend.
type Config struct {
	SchedulerAddress  string            `yaml:"scheduler_address"`
	DNSLookupPeriod   time.Duration     `yaml:"scheduler_dns_lookup_period"`
	WorkerConcurrency int               `yaml:"scheduler_worker_concurrency"`
	GRPCClientConfig  grpcclient.Config `yaml:"grpc_client_config"`

	// Used to find local IP address, that is sent to scheduler and querier-worker.
	InfNames []string `yaml:"instance_interface_names"`

	// If set, address is not computed from interfaces.
	Addr string `yaml:"address" doc:"hidden"`
	Port int    `doc:"hidden"`
}

func (cfg *Config) RegisterFlags(f *flag.FlagSet) {
	f.StringVar(&cfg.SchedulerAddress, "frontend.scheduler-address", "", "DNS hostname used for finding query-schedulers.")
	f.DurationVar(&cfg.DNSLookupPeriod, "frontend.scheduler-dns-lookup-period", 10*time.Second, "How often to resolve the scheduler-address, in order to look for new query-scheduler instances. Also used to determine how often to poll the scheduler-ring for addresses if the scheduler-ring is configured.")
	f.IntVar(&cfg.WorkerConcurrency, "frontend.scheduler-worker-concurrency", 5, "Number of concurrent workers forwarding queries to single query-scheduler.")

	cfg.InfNames = netutil.PrivateNetworkInterfacesWithFallback([]string{"eth0", "en0"}, util_log.Logger)
	f.Var((*flagext.StringSlice)(&cfg.InfNames), "frontend.instance-interface-names", "Name of network interface to read address from. This address is sent to query-scheduler and querier, which uses it to send the query response back to query-frontend.")
	f.StringVar(&cfg.Addr, "frontend.instance-addr", "", "IP address to advertise to querier (via scheduler) (resolved via interfaces by default).")
	f.IntVar(&cfg.Port, "frontend.instance-port", 0, "Port to advertise to querier (via scheduler) (defaults to server.grpc-listen-port).")

	cfg.GRPCClientConfig.RegisterFlagsWithPrefix("frontend.grpc-client-config", f)
}

// Frontend implements GrpcRoundTripper. It queues HTTP requests,
// dispatches them to backends via gRPC, and handles retries for requests which failed.
type Frontend struct {
	services.Service

	cfg Config
	log log.Logger

	lastQueryID atomic.Uint64

	// frontend workers will read from this channel, and send request to scheduler.
	requestsCh chan *frontendRequest

	schedulerWorkers *frontendSchedulerWorkers
	requests         *requestsInProgress
}

type frontendRequest struct {
	queryID      uint64
	request      *httpgrpc.HTTPRequest
	userID       string
	statsEnabled bool

	cancel context.CancelFunc

	enqueue  chan enqueueResult
	response chan *frontendv2pb.QueryResultRequest
}

type enqueueStatus int

const (
	// Sent to scheduler successfully, and frontend should wait for response now.
	waitForResponse enqueueStatus = iota

	// Failed to forward request to scheduler, frontend will try again.
	failed
)

type enqueueResult struct {
	status enqueueStatus

	cancelCh chan<- uint64 // Channel that can be used for request cancellation. If nil, cancellation is not possible.
}

// NewFrontend creates a new frontend.
func NewFrontend(cfg Config, ring ring.ReadRing, log log.Logger, reg prometheus.Registerer) (*Frontend, error) {
	requestsCh := make(chan *frontendRequest)

	schedulerWorkers, err := newFrontendSchedulerWorkers(cfg, fmt.Sprintf("%s:%d", cfg.Addr, cfg.Port), ring, requestsCh, log)
	if err != nil {
		return nil, err
	}

	f := &Frontend{
		cfg:              cfg,
		log:              log,
		requestsCh:       requestsCh,
		schedulerWorkers: schedulerWorkers,
		requests:         newRequestsInProgress(),
	}
	// Randomize to avoid getting responses from queries sent before restart, which could lead to mixing results
	// between different queries. Note that frontend verifies the user, so it cannot leak results between tenants.
	// This isn't perfect, but better than nothing.
	f.lastQueryID.Store(rand.Uint64())

	promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
		Name: "cortex_query_frontend_queries_in_progress",
		Help: "Number of queries in progress handled by this frontend.",
	}, func() float64 {
		return float64(f.requests.count())
	})

	promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
		Name: "cortex_query_frontend_connected_schedulers",
		Help: "Number of schedulers this frontend is connected to.",
	}, func() float64 {
		return float64(f.schedulerWorkers.getWorkersCount())
	})

	f.Service = services.NewIdleService(f.starting, f.stopping)
	return f, nil
}

func (f *Frontend) starting(ctx context.Context) error {
	return errors.Wrap(services.StartAndAwaitRunning(ctx, f.schedulerWorkers), "failed to start frontend scheduler workers")
}

func (f *Frontend) stopping(_ error) error {
	return errors.Wrap(services.StopAndAwaitTerminated(context.Background(), f.schedulerWorkers), "failed to stop frontend scheduler workers")
}

// RoundTripGRPC round trips a proto (instead of a HTTP request).
func (f *Frontend) RoundTripGRPC(ctx context.Context, req *httpgrpc.HTTPRequest) (*httpgrpc.HTTPResponse, error) {
	if s := f.State(); s != services.Running {
		return nil, fmt.Errorf("frontend not running: %v", s)
	}

	tenantIDs, err := tenant.TenantIDs(ctx)
	if err != nil {
		return nil, err
	}
	userID := tenant.JoinTenantIDs(tenantIDs)

	// Propagate trace context in gRPC too - this will be ignored if using HTTP.
	tracer, span := opentracing.GlobalTracer(), opentracing.SpanFromContext(ctx)
	if tracer != nil && span != nil {
		carrier := (*lokigrpc.HeadersCarrier)(req)
		if err := tracer.Inject(span.Context(), opentracing.HTTPHeaders, carrier); err != nil {
			return nil, err
		}
	}

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	freq := &frontendRequest{
		queryID:      f.lastQueryID.Inc(),
		request:      req,
		userID:       userID,
		statsEnabled: stats.IsEnabled(ctx),

		cancel: cancel,

		// Buffer of 1 to ensure response or error can be written to the channel
		// even if this goroutine goes away due to client context cancellation.
		enqueue:  make(chan enqueueResult, 1),
		response: make(chan *frontendv2pb.QueryResultRequest, 1),
	}

	f.requests.put(freq)
	defer f.requests.delete(freq.queryID)

	retries := f.cfg.WorkerConcurrency + 1 // To make sure we hit at least two different schedulers.

enqueueAgain:
	var cancelCh chan<- uint64
	select {
	case <-ctx.Done():
		return nil, ctx.Err()

	case f.requestsCh <- freq:
		// Enqueued, let's wait for response.
		enqRes := <-freq.enqueue

		if enqRes.status == waitForResponse {
			cancelCh = enqRes.cancelCh
			break // go wait for response.
		} else if enqRes.status == failed {
			retries--
			if retries > 0 {
				goto enqueueAgain
			}
		}

		return nil, httpgrpc.Errorf(http.StatusInternalServerError, "failed to enqueue request")
	}

	select {
	case <-ctx.Done():
		if cancelCh != nil {
			select {
			case cancelCh <- freq.queryID:
				// cancellation sent.
			default:
				// failed to cancel, ignore.
				level.Warn(f.log).Log("msg", "failed to send cancellation request to scheduler, queue full")
			}
		}
		return nil, ctx.Err()

	case resp := <-freq.response:
		if stats.ShouldTrackHTTPGRPCResponse(resp.HttpResponse) {
			stats := stats.FromContext(ctx)
			stats.Merge(resp.Stats) // Safe if stats is nil.
		}

		return resp.HttpResponse, nil
	}
}

func (f *Frontend) QueryResult(ctx context.Context, qrReq *frontendv2pb.QueryResultRequest) (*frontendv2pb.QueryResultResponse, error) {
	tenantIDs, err := tenant.TenantIDs(ctx)
	if err != nil {
		return nil, err
	}
	userID := tenant.JoinTenantIDs(tenantIDs)

	req := f.requests.get(qrReq.QueryID)
	// It is possible that some old response belonging to different user was received, if frontend has restarted.
	// To avoid leaking query results between users, we verify the user here.
	// To avoid mixing results from different queries, we randomize queryID counter on start.
	if req != nil && req.userID == userID {
		select {
		case req.response <- qrReq:
			// Should always be possible, unless QueryResult is called multiple times with the same queryID.
		default:
			level.Warn(f.log).Log("msg", "failed to write query result to the response channel", "queryID", qrReq.QueryID, "user", userID)
		}
	}

	return &frontendv2pb.QueryResultResponse{}, nil
}

// CheckReady determines if the query frontend is ready.  Function parameters/return
// chosen to match the same method in the ingester
func (f *Frontend) CheckReady(_ context.Context) error {
	workers := f.schedulerWorkers.getWorkersCount()

	// If frontend is connected to at least one scheduler, we are ready.
	if workers > 0 {
		return nil
	}

	msg := fmt.Sprintf("not ready: number of schedulers this worker is connected to is %d", workers)
	level.Info(f.log).Log("msg", msg)
	return errors.New(msg)
}

const stripeSize = 1 << 6

type requestsInProgress struct {
	locks    []sync.Mutex
	requests []map[uint64]*frontendRequest
}

func newRequestsInProgress() *requestsInProgress {
	x := &requestsInProgress{
		requests: make([]map[uint64]*frontendRequest, stripeSize),
		locks:    make([]sync.Mutex, stripeSize),
	}

	for i := range x.requests {
		x.requests[i] = map[uint64]*frontendRequest{}
	}

	return x
}

func (r *requestsInProgress) count() (res int) {
	for i := range r.requests {
		r.locks[i].Lock()
		res += len(r.requests[i])
		r.locks[i].Unlock()
	}
	return
}

func (r *requestsInProgress) put(req *frontendRequest) {
	i := req.queryID & uint64(stripeSize-1)
	r.locks[i].Lock()
	r.requests[i][req.queryID] = req
	r.locks[i].Unlock()
}

func (r *requestsInProgress) delete(queryID uint64) {
	i := queryID & uint64(stripeSize-1)
	r.locks[i].Lock()
	delete(r.requests[i], queryID)
	r.locks[i].Unlock()

}

func (r *requestsInProgress) get(queryID uint64) *frontendRequest {
	i := queryID & uint64(stripeSize-1)
	r.locks[i].Lock()
	req := r.requests[i][queryID]
	r.locks[i].Unlock()
	return req
}
<|endoftext|>


<commit_before>package payment_test

import (
	"database/sql"
	. "github.com/fritzpay/paymentd/pkg/paymentd/payment"
	"github.com/fritzpay/paymentd/pkg/paymentd/project"
	"github.com/fritzpay/paymentd/pkg/testutil"
	. "github.com/smartystreets/goconvey/convey"
	"testing"
)

func TestPaymentSQL(t *testing.T) {
	Convey("Given a payment DB", t, testutil.WithPaymentDB(t, func(db *sql.DB) {
		Reset(func() {
			db.Close()
		})
		Convey("Given a principal DB", testutil.WithPrincipalDB(t, func(prDB *sql.DB) {
			Reset(func() {
				prDB.Close()
			})
			Convey("Given a test project", WithTestProject(db, prDB, func(proj project.Project) {
				Convey("Given a transaction", func() {
					tx, err := db.Begin()
					So(err, ShouldBeNil)

					Reset(func() {
						err = tx.Rollback()
						So(err, ShouldBeNil)
					})

					Convey("Given a test payment", WithTestPayment(tx, proj, func(p Payment) {
						Convey("When selecting a payment by ident", func() {
							p2, err := PaymentByProjectIDAndIdentTx(tx, proj.ID, p.Ident)
							Convey("It should succeed", func() {
								So(err, ShouldBeNil)
								Convey("It should match the original payment", func() {
									So(p2.ID(), ShouldEqual, p.ID())
								})
							})
						})
					}))
				})
			}))
		}))
	}))
}
<commit_msg>bugfix: add failing test for incorrectly set tx timestamp<commit_after>package payment_test

import (
	"database/sql"
	. "github.com/fritzpay/paymentd/pkg/paymentd/payment"
	"github.com/fritzpay/paymentd/pkg/paymentd/project"
	"github.com/fritzpay/paymentd/pkg/testutil"
	. "github.com/smartystreets/goconvey/convey"
	"testing"
	"time"
)

func TestPaymentSQL(t *testing.T) {
	Convey("Given a payment DB", t, testutil.WithPaymentDB(t, func(db *sql.DB) {
		Reset(func() {
			db.Close()
		})
		Convey("Given a principal DB", testutil.WithPrincipalDB(t, func(prDB *sql.DB) {
			Reset(func() {
				prDB.Close()
			})
			Convey("Given a test project", WithTestProject(db, prDB, func(proj project.Project) {
				Convey("Given a transaction", func() {
					tx, err := db.Begin()
					So(err, ShouldBeNil)

					Reset(func() {
						err = tx.Rollback()
						So(err, ShouldBeNil)
					})

					Convey("Given a test payment", WithTestPayment(tx, proj, func(p Payment) {
						Convey("When selecting a payment by ident", func() {
							p2, err := PaymentByProjectIDAndIdentTx(tx, proj.ID, p.Ident)
							Convey("It should succeed", func() {
								So(err, ShouldBeNil)
								Convey("It should match the original payment", func() {
									So(p2.ID(), ShouldEqual, p.ID())
								})
							})
						})

						Convey("Given the test payment has a transaction", func() {
							paymentTx := p.NewTransaction(PaymentStatusPaid)
							paymentTx.Timestamp = time.Unix(9876, 0)
							err = InsertPaymentTransactionTx(tx, paymentTx)
							So(err, ShouldBeNil)

							Convey("When selecting the payment", func() {
								p2, err := PaymentByIDTx(tx, p.PaymentID())
								So(err, ShouldBeNil)

								Convey("The transaction values should be set in the payment", func() {
									So(p2.TransactionTimestamp.Unix(), ShouldEqual, 9876)
									So(p2.Status, ShouldEqual, PaymentStatusPaid)
								})
							})
						})
					}))
				})
			}))
		}))
	}))
}
<|endoftext|>


<commit_before>// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.

package cluster

import (
	"context"

	jobclient "openpitrix.io/openpitrix/pkg/client/job"
	providerclient "openpitrix.io/openpitrix/pkg/client/runtime_provider"
	"openpitrix.io/openpitrix/pkg/constants"
	"openpitrix.io/openpitrix/pkg/gerr"
	"openpitrix.io/openpitrix/pkg/logger"
	"openpitrix.io/openpitrix/pkg/models"
	"openpitrix.io/openpitrix/pkg/pb"
	"openpitrix.io/openpitrix/pkg/pi"
	"openpitrix.io/openpitrix/pkg/util/jsonutil"
	"openpitrix.io/openpitrix/pkg/util/pbutil"
)

func (f *Frontgate) parseConf(subnetId, conf string) (string, error) {
	decodeConf := make(map[string]interface{})
	err := jsonutil.Decode([]byte(conf), &decodeConf)
	if err != nil {
		return "", err
	}
	decodeConf["version_id"] = constants.FrontgateVersionId
	decodeConf["subnet"] = subnetId
	resConf := jsonutil.ToString(&decodeConf)
	return resConf, nil
}

func (f *Frontgate) getConf(ctx context.Context, subnetId, runtimeUrl, runtimeZone string) (string, error) {
	conf := constants.FrontgateDefaultConf
	if pi.Global().GlobalConfig().Cluster.FrontgateConf != "" {
		conf = pi.Global().GlobalConfig().Cluster.FrontgateConf
	}

	imageConfig, err := pi.Global().GlobalConfig().GetRuntimeImageIdAndUrl(runtimeUrl, runtimeZone)
	if err != nil {
		return "", err
	}
	if imageConfig.FrontgateConf != "" {
		conf = imageConfig.FrontgateConf
	}

	return f.parseConf(subnetId, conf)
}

func (f *Frontgate) CreateCluster(ctx context.Context, clusterWrapper *models.ClusterWrapper) (string, error) {
	clusterId := models.NewClusterId()

	conf, err := f.getConf(ctx, clusterWrapper.Cluster.SubnetId, f.Runtime.RuntimeUrl, f.Runtime.Zone)
	if err != nil {
		logger.Error(ctx, "Get frontgate cluster conf failed. ")
		return clusterId, err
	}
	frontgateWrapper := new(models.ClusterWrapper)
	providerClient, err := providerclient.NewRuntimeProviderManagerClient()
	if err != nil {
		return clusterId, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError)
	}
	response, err := providerClient.ParseClusterConf(ctx, &pb.ParseClusterConfRequest{
		RuntimeId: pbutil.ToProtoString(clusterWrapper.Cluster.RuntimeId),
		VersionId: pbutil.ToProtoString(constants.FrontgateVersionId),
		Conf:      pbutil.ToProtoString(conf),
		Cluster:   models.ClusterWrapperToPb(frontgateWrapper),
	})
	if err != nil {
		logger.Error(ctx, "Parse frontgate cluster conf failed.")
		return clusterId, err
	}

	frontgateWrapper = models.PbToClusterWrapper(response.Cluster)
	frontgateWrapper.Cluster.Zone = clusterWrapper.Cluster.Zone
	frontgateWrapper.Cluster.Debug = clusterWrapper.Cluster.Debug
	frontgateWrapper.Cluster.ClusterId = clusterId
	frontgateWrapper.Cluster.SubnetId = clusterWrapper.Cluster.SubnetId
	frontgateWrapper.Cluster.VpcId = clusterWrapper.Cluster.VpcId
	frontgateWrapper.Cluster.Owner = clusterWrapper.Cluster.Owner
	frontgateWrapper.Cluster.ClusterType = constants.FrontgateClusterType
	frontgateWrapper.Cluster.FrontgateId = ""
	frontgateWrapper.Cluster.RuntimeId = f.Runtime.RuntimeId

	err = RegisterClusterWrapper(ctx, frontgateWrapper)
	if err != nil {
		return clusterId, err
	}

	directive := jsonutil.ToString(frontgateWrapper)
	newJob := models.NewJob(
		constants.PlaceHolder,
		clusterId,
		frontgateWrapper.Cluster.AppId,
		frontgateWrapper.Cluster.VersionId,
		constants.ActionCreateCluster,
		directive,
		f.Runtime.Runtime.Provider,
		frontgateWrapper.Cluster.OwnerPath,
		frontgateWrapper.Cluster.RuntimeId,
	)

	_, err = jobclient.SendJob(ctx, newJob)
	return clusterId, err
}

func (f *Frontgate) StartCluster(ctx context.Context, frontgate *models.Cluster) error {
	clusterWrapper, err := getClusterWrapper(ctx, frontgate.ClusterId)
	if err != nil {
		return err
	}

	directive := jsonutil.ToString(clusterWrapper)
	newJob := models.NewJob(
		constants.PlaceHolder,
		frontgate.ClusterId,
		frontgate.AppId,
		frontgate.VersionId,
		constants.ActionStartClusters,
		directive,
		f.Runtime.Runtime.Provider,
		frontgate.OwnerPath,
		frontgate.RuntimeId,
	)

	_, err = jobclient.SendJob(ctx, newJob)
	return err
}

func (f *Frontgate) RecoverCluster(ctx context.Context, frontgate *models.Cluster) error {
	clusterWrapper, err := getClusterWrapper(ctx, frontgate.ClusterId)
	if err != nil {
		return err
	}

	directive := jsonutil.ToString(clusterWrapper)
	newJob := models.NewJob(
		constants.PlaceHolder,
		frontgate.ClusterId,
		frontgate.AppId,
		frontgate.VersionId,
		constants.ActionRecoverClusters,
		directive,
		f.Runtime.Runtime.Provider,
		frontgate.OwnerPath,
		frontgate.RuntimeId,
	)

	_, err = jobclient.SendJob(ctx, newJob)
	return err
}
<commit_msg>Register owner path when create frontgate<commit_after>// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.

package cluster

import (
	"context"

	jobclient "openpitrix.io/openpitrix/pkg/client/job"
	providerclient "openpitrix.io/openpitrix/pkg/client/runtime_provider"
	"openpitrix.io/openpitrix/pkg/constants"
	"openpitrix.io/openpitrix/pkg/gerr"
	"openpitrix.io/openpitrix/pkg/logger"
	"openpitrix.io/openpitrix/pkg/models"
	"openpitrix.io/openpitrix/pkg/pb"
	"openpitrix.io/openpitrix/pkg/pi"
	"openpitrix.io/openpitrix/pkg/util/jsonutil"
	"openpitrix.io/openpitrix/pkg/util/pbutil"
)

func (f *Frontgate) parseConf(subnetId, conf string) (string, error) {
	decodeConf := make(map[string]interface{})
	err := jsonutil.Decode([]byte(conf), &decodeConf)
	if err != nil {
		return "", err
	}
	decodeConf["version_id"] = constants.FrontgateVersionId
	decodeConf["subnet"] = subnetId
	resConf := jsonutil.ToString(&decodeConf)
	return resConf, nil
}

func (f *Frontgate) getConf(ctx context.Context, subnetId, runtimeUrl, runtimeZone string) (string, error) {
	conf := constants.FrontgateDefaultConf
	if pi.Global().GlobalConfig().Cluster.FrontgateConf != "" {
		conf = pi.Global().GlobalConfig().Cluster.FrontgateConf
	}

	imageConfig, err := pi.Global().GlobalConfig().GetRuntimeImageIdAndUrl(runtimeUrl, runtimeZone)
	if err != nil {
		return "", err
	}
	if imageConfig.FrontgateConf != "" {
		conf = imageConfig.FrontgateConf
	}

	return f.parseConf(subnetId, conf)
}

func (f *Frontgate) CreateCluster(ctx context.Context, clusterWrapper *models.ClusterWrapper) (string, error) {
	clusterId := models.NewClusterId()

	conf, err := f.getConf(ctx, clusterWrapper.Cluster.SubnetId, f.Runtime.RuntimeUrl, f.Runtime.Zone)
	if err != nil {
		logger.Error(ctx, "Get frontgate cluster conf failed. ")
		return clusterId, err
	}
	frontgateWrapper := new(models.ClusterWrapper)
	providerClient, err := providerclient.NewRuntimeProviderManagerClient()
	if err != nil {
		return clusterId, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError)
	}
	response, err := providerClient.ParseClusterConf(ctx, &pb.ParseClusterConfRequest{
		RuntimeId: pbutil.ToProtoString(clusterWrapper.Cluster.RuntimeId),
		VersionId: pbutil.ToProtoString(constants.FrontgateVersionId),
		Conf:      pbutil.ToProtoString(conf),
		Cluster:   models.ClusterWrapperToPb(frontgateWrapper),
	})
	if err != nil {
		logger.Error(ctx, "Parse frontgate cluster conf failed.")
		return clusterId, err
	}

	frontgateWrapper = models.PbToClusterWrapper(response.Cluster)
	frontgateWrapper.Cluster.Zone = clusterWrapper.Cluster.Zone
	frontgateWrapper.Cluster.Debug = clusterWrapper.Cluster.Debug
	frontgateWrapper.Cluster.ClusterId = clusterId
	frontgateWrapper.Cluster.SubnetId = clusterWrapper.Cluster.SubnetId
	frontgateWrapper.Cluster.VpcId = clusterWrapper.Cluster.VpcId
	frontgateWrapper.Cluster.Owner = clusterWrapper.Cluster.Owner
	frontgateWrapper.Cluster.OwnerPath = clusterWrapper.Cluster.OwnerPath
	frontgateWrapper.Cluster.ClusterType = constants.FrontgateClusterType
	frontgateWrapper.Cluster.FrontgateId = ""
	frontgateWrapper.Cluster.RuntimeId = f.Runtime.RuntimeId

	err = RegisterClusterWrapper(ctx, frontgateWrapper)
	if err != nil {
		return clusterId, err
	}

	directive := jsonutil.ToString(frontgateWrapper)
	newJob := models.NewJob(
		constants.PlaceHolder,
		clusterId,
		frontgateWrapper.Cluster.AppId,
		frontgateWrapper.Cluster.VersionId,
		constants.ActionCreateCluster,
		directive,
		f.Runtime.Runtime.Provider,
		frontgateWrapper.Cluster.OwnerPath,
		frontgateWrapper.Cluster.RuntimeId,
	)

	_, err = jobclient.SendJob(ctx, newJob)
	return clusterId, err
}

func (f *Frontgate) StartCluster(ctx context.Context, frontgate *models.Cluster) error {
	clusterWrapper, err := getClusterWrapper(ctx, frontgate.ClusterId)
	if err != nil {
		return err
	}

	directive := jsonutil.ToString(clusterWrapper)
	newJob := models.NewJob(
		constants.PlaceHolder,
		frontgate.ClusterId,
		frontgate.AppId,
		frontgate.VersionId,
		constants.ActionStartClusters,
		directive,
		f.Runtime.Runtime.Provider,
		frontgate.OwnerPath,
		frontgate.RuntimeId,
	)

	_, err = jobclient.SendJob(ctx, newJob)
	return err
}

func (f *Frontgate) RecoverCluster(ctx context.Context, frontgate *models.Cluster) error {
	clusterWrapper, err := getClusterWrapper(ctx, frontgate.ClusterId)
	if err != nil {
		return err
	}

	directive := jsonutil.ToString(clusterWrapper)
	newJob := models.NewJob(
		constants.PlaceHolder,
		frontgate.ClusterId,
		frontgate.AppId,
		frontgate.VersionId,
		constants.ActionRecoverClusters,
		directive,
		f.Runtime.Runtime.Provider,
		frontgate.OwnerPath,
		frontgate.RuntimeId,
	)

	_, err = jobclient.SendJob(ctx, newJob)
	return err
}
<|endoftext|>


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

package test

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

	"v.io/jiri/collect"
	"v.io/jiri/project"
	"v.io/jiri/tool"
	"v.io/x/devtools/internal/test"
	"v.io/x/devtools/internal/xunit"
)

var (
	mirrors = []Mirror{
		Mirror{
			name:         "browser",
			googlesource: "https://vanadium.googlesource.com/release.projects.browser",
			github:       "git@github.com:vanadium/browser.git",
		},
		Mirror{
			name:         "chat",
			googlesource: "https://vanadium.googlesource.com/release.projects.chat",
			github:       "git@github.com:vanadium/chat.git",
		},
		Mirror{
			name:         "docs",
			googlesource: "https://vanadium.googlesource.com/docs",
			github:       "git@github.com:vanadium/docs.git",
		},
		Mirror{
			name:         "go.devtools",
			googlesource: "https://vanadium.googlesource.com/release.go.x.devtools",
			github:       "git@github.com:vanadium/go.devtools.git",
		},
		Mirror{
			name:         "go.jiri",
			googlesource: "https://vanadium.googlesource.com/release.go.jiri",
			github:       "git@github.com:vanadium/go.jiri.git",
		},
		Mirror{
			name:         "go.lib",
			googlesource: "https://vanadium.googlesource.com/release.go.x.lib",
			github:       "git@github.com:vanadium/go.lib.git",
		},
		Mirror{
			name:         "go.ref",
			googlesource: "https://vanadium.googlesource.com/release.go.x.ref",
			github:       "git@github.com:vanadium/go.ref.git",
		},
		Mirror{
			name:         "go.v23",
			googlesource: "https://vanadium.googlesource.com/release.go.v23",
			github:       "git@github.com:vanadium/go.v23.git",
		},
		Mirror{
			name:         "js",
			googlesource: "https://vanadium.googlesource.com/release.js.core",
			github:       "git@github.com:vanadium/js.git",
		},
		Mirror{
			name:         "js.syncbase",
			googlesource: "https://vanadium.googlesource.com/release.js.syncbase",
			github:       "git@github.com:vanadium/js.syncbase.git",
		},
		Mirror{
			name:         "mojo.syncbase",
			googlesource: "https://vanadium.googlesource.com/release.mojo.syncbase",
			github:       "git@github.com:vanadium/mojo.syncbase.git",
		},
		Mirror{
			name:         "pipe2browser",
			googlesource: "https://vanadium.googlesource.com/release.projects.pipe2browser",
			github:       "git@github.com:vanadium/pipe2browser.git",
		},
		Mirror{
			name:         "playground",
			googlesource: "https://vanadium.googlesource.com/release.projects.playground",
			github:       "git@github.com:vanadium/playground.git",
		},
		Mirror{
			name:         "reader",
			googlesource: "https://vanadium.googlesource.com/release.projects.reader",
			github:       "git@github.com:vanadium/reader.git",
		},
		Mirror{
			name:         "third_party",
			googlesource: "https://vanadium.googlesource.com/third_party",
			github:       "git@github.com:vanadium/third_party.git",
		},
		Mirror{
			name:         "todos",
			googlesource: "https://vanadium.googlesource.com/release.projects.todos",
			github:       "git@github.com:vanadium/todos.git",
		},
		Mirror{
			name:         "www",
			googlesource: "https://vanadium.googlesource.com/www",
			github:       "git@github.com:vanadium/www.git",
		},
	}
)

type Mirror struct {
	name, googlesource, github string
}

// vanadiumGitHubMirror mirrors googlesource.com vanadium projects to
// github.com.
func vanadiumGitHubMirror(ctx *tool.Context, testName string, _ ...Opt) (_ *test.Result, e error) {
	// Initialize the test/task.
	cleanup, err := initTest(ctx, testName, nil)
	if err != nil {
		return nil, internalTestError{err, "Init"}
	}
	defer collect.Error(func() error { return cleanup() }, &e)

	root, err := project.JiriRoot()
	if err != nil {
		return nil, internalTestError{err, "JiriRoot"}
	}

	projects := filepath.Join(root, "projects")
	mode := os.FileMode(0755)
	if err := ctx.Run().MkdirAll(projects, mode); err != nil {
		return nil, internalTestError{err, "MkdirAll"}
	}

	allPassed := true
	suites := []xunit.TestSuite{}
	for _, mirror := range mirrors {
		suite, err := sync(ctx, mirror, projects)
		if err != nil {
			return nil, internalTestError{err, "sync"}
		}

		allPassed = allPassed && (suite.Failures == 0)
		suites = append(suites, *suite)
	}

	if err := xunit.CreateReport(ctx, testName, suites); err != nil {
		return nil, err
	}

	if !allPassed {
		return &test.Result{Status: test.Failed}, nil
	}

	return &test.Result{Status: test.Passed}, nil
}

func sync(ctx *tool.Context, mirror Mirror, projects string) (*xunit.TestSuite, error) {
	suite := xunit.TestSuite{Name: mirror.name}
	dirname := filepath.Join(projects, mirror.name)

	// If dirname does not exist `git clone` otherwise `git pull`.
	if _, err := ctx.Run().Stat(dirname); err != nil {
		if !os.IsNotExist(err) {
			return nil, internalTestError{err, "stat"}
		}

		err := clone(ctx, mirror, projects)
		testCase := makeTestCase("clone", err)
		if err != nil {
			suite.Failures++
		}
		suite.Cases = append(suite.Cases, *testCase)
	} else {
		err := pull(ctx, mirror, projects)
		testCase := makeTestCase("pull", err)
		if err != nil {
			suite.Failures++
		}
		suite.Cases = append(suite.Cases, *testCase)
	}

	err := push(ctx, mirror, projects)
	testCase := makeTestCase("push", err)
	if err != nil {
		suite.Failures++
	}
	suite.Cases = append(suite.Cases, *testCase)

	return &suite, nil
}

func makeTestCase(action string, err error) *xunit.TestCase {
	c := xunit.TestCase{
		Classname: "git",
		Name:      action,
	}

	if err != nil {
		f := xunit.Failure{
			Message: "git error",
			Data:    fmt.Sprintf("%v", err),
		}
		c.Failures = append(c.Failures, f)
	}

	return &c
}

func clone(ctx *tool.Context, mirror Mirror, projects string) error {
	dirname := filepath.Join(projects, mirror.name)
	return ctx.Git().Clone(mirror.googlesource, dirname)
}

func pull(ctx *tool.Context, mirror Mirror, projects string) error {
	dirname := filepath.Join(projects, mirror.name)
	opts := tool.RootDirOpt(dirname)
	return ctx.Git(opts).Pull("origin", "master")
}

func push(ctx *tool.Context, mirror Mirror, projects string) error {
	dirname := filepath.Join(projects, mirror.name)
	opts := tool.RootDirOpt(dirname)
	return ctx.Git(opts).Push(mirror.github, "master")
}
<commit_msg>add java mirroring<commit_after>// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package test

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

	"v.io/jiri/collect"
	"v.io/jiri/project"
	"v.io/jiri/tool"
	"v.io/x/devtools/internal/test"
	"v.io/x/devtools/internal/xunit"
)

var (
	mirrors = []Mirror{
		Mirror{
			name:         "browser",
			googlesource: "https://vanadium.googlesource.com/release.projects.browser",
			github:       "git@github.com:vanadium/browser.git",
		},
		Mirror{
			name:         "chat",
			googlesource: "https://vanadium.googlesource.com/release.projects.chat",
			github:       "git@github.com:vanadium/chat.git",
		},
		Mirror{
			name:         "docs",
			googlesource: "https://vanadium.googlesource.com/docs",
			github:       "git@github.com:vanadium/docs.git",
		},
		Mirror{
			name:         "go.devtools",
			googlesource: "https://vanadium.googlesource.com/release.go.x.devtools",
			github:       "git@github.com:vanadium/go.devtools.git",
		},
		Mirror{
			name:         "go.jiri",
			googlesource: "https://vanadium.googlesource.com/release.go.jiri",
			github:       "git@github.com:vanadium/go.jiri.git",
		},
		Mirror{
			name:         "go.lib",
			googlesource: "https://vanadium.googlesource.com/release.go.x.lib",
			github:       "git@github.com:vanadium/go.lib.git",
		},
		Mirror{
			name:         "go.ref",
			googlesource: "https://vanadium.googlesource.com/release.go.x.ref",
			github:       "git@github.com:vanadium/go.ref.git",
		},
		Mirror{
			name:         "go.v23",
			googlesource: "https://vanadium.googlesource.com/release.go.v23",
			github:       "git@github.com:vanadium/go.v23.git",
		},
		Mirror{
			name:         "java",
			googlesource: "https://vanadium.googlesource.com/release.java",
			github:       "git@github.com:vanadium/java",
		},
		Mirror{
			name:         "js",
			googlesource: "https://vanadium.googlesource.com/release.js.core",
			github:       "git@github.com:vanadium/js.git",
		},
		Mirror{
			name:         "js.syncbase",
			googlesource: "https://vanadium.googlesource.com/release.js.syncbase",
			github:       "git@github.com:vanadium/js.syncbase.git",
		},
		Mirror{
			name:         "mojo.syncbase",
			googlesource: "https://vanadium.googlesource.com/release.mojo.syncbase",
			github:       "git@github.com:vanadium/mojo.syncbase.git",
		},
		Mirror{
			name:         "pipe2browser",
			googlesource: "https://vanadium.googlesource.com/release.projects.pipe2browser",
			github:       "git@github.com:vanadium/pipe2browser.git",
		},
		Mirror{
			name:         "playground",
			googlesource: "https://vanadium.googlesource.com/release.projects.playground",
			github:       "git@github.com:vanadium/playground.git",
		},
		Mirror{
			name:         "reader",
			googlesource: "https://vanadium.googlesource.com/release.projects.reader",
			github:       "git@github.com:vanadium/reader.git",
		},
		Mirror{
			name:         "third_party",
			googlesource: "https://vanadium.googlesource.com/third_party",
			github:       "git@github.com:vanadium/third_party.git",
		},
		Mirror{
			name:         "todos",
			googlesource: "https://vanadium.googlesource.com/release.projects.todos",
			github:       "git@github.com:vanadium/todos.git",
		},
		Mirror{
			name:         "www",
			googlesource: "https://vanadium.googlesource.com/www",
			github:       "git@github.com:vanadium/www.git",
		},
	}
)

type Mirror struct {
	name, googlesource, github string
}

// vanadiumGitHubMirror mirrors googlesource.com vanadium projects to
// github.com.
func vanadiumGitHubMirror(ctx *tool.Context, testName string, _ ...Opt) (_ *test.Result, e error) {
	// Initialize the test/task.
	cleanup, err := initTest(ctx, testName, nil)
	if err != nil {
		return nil, internalTestError{err, "Init"}
	}
	defer collect.Error(func() error { return cleanup() }, &e)

	root, err := project.JiriRoot()
	if err != nil {
		return nil, internalTestError{err, "JiriRoot"}
	}

	projects := filepath.Join(root, "projects")
	mode := os.FileMode(0755)
	if err := ctx.Run().MkdirAll(projects, mode); err != nil {
		return nil, internalTestError{err, "MkdirAll"}
	}

	allPassed := true
	suites := []xunit.TestSuite{}
	for _, mirror := range mirrors {
		suite, err := sync(ctx, mirror, projects)
		if err != nil {
			return nil, internalTestError{err, "sync"}
		}

		allPassed = allPassed && (suite.Failures == 0)
		suites = append(suites, *suite)
	}

	if err := xunit.CreateReport(ctx, testName, suites); err != nil {
		return nil, err
	}

	if !allPassed {
		return &test.Result{Status: test.Failed}, nil
	}

	return &test.Result{Status: test.Passed}, nil
}

func sync(ctx *tool.Context, mirror Mirror, projects string) (*xunit.TestSuite, error) {
	suite := xunit.TestSuite{Name: mirror.name}
	dirname := filepath.Join(projects, mirror.name)

	// If dirname does not exist `git clone` otherwise `git pull`.
	if _, err := ctx.Run().Stat(dirname); err != nil {
		if !os.IsNotExist(err) {
			return nil, internalTestError{err, "stat"}
		}

		err := clone(ctx, mirror, projects)
		testCase := makeTestCase("clone", err)
		if err != nil {
			suite.Failures++
		}
		suite.Cases = append(suite.Cases, *testCase)
	} else {
		err := pull(ctx, mirror, projects)
		testCase := makeTestCase("pull", err)
		if err != nil {
			suite.Failures++
		}
		suite.Cases = append(suite.Cases, *testCase)
	}

	err := push(ctx, mirror, projects)
	testCase := makeTestCase("push", err)
	if err != nil {
		suite.Failures++
	}
	suite.Cases = append(suite.Cases, *testCase)

	return &suite, nil
}

func makeTestCase(action string, err error) *xunit.TestCase {
	c := xunit.TestCase{
		Classname: "git",
		Name:      action,
	}

	if err != nil {
		f := xunit.Failure{
			Message: "git error",
			Data:    fmt.Sprintf("%v", err),
		}
		c.Failures = append(c.Failures, f)
	}

	return &c
}

func clone(ctx *tool.Context, mirror Mirror, projects string) error {
	dirname := filepath.Join(projects, mirror.name)
	return ctx.Git().Clone(mirror.googlesource, dirname)
}

func pull(ctx *tool.Context, mirror Mirror, projects string) error {
	dirname := filepath.Join(projects, mirror.name)
	opts := tool.RootDirOpt(dirname)
	return ctx.Git(opts).Pull("origin", "master")
}

func push(ctx *tool.Context, mirror Mirror, projects string) error {
	dirname := filepath.Join(projects, mirror.name)
	opts := tool.RootDirOpt(dirname)
	return ctx.Git(opts).Push(mirror.github, "master")
}
<|endoftext|>