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

package templates

import (
	"fmt"
)

var masterTemplate = fmt.Sprintf(`<!DOCTYPE HTML>

	<meta charset="utf-8">
	<base href="{{ .BaseUrl }}">

	<title>{{.Title}}</title>

	<link rel="schema.DC" href="http://purl.org/dc/terms/">
	<meta name="DC.date" content="{{.CreationDate}}">

	{{if .GeoLocation }}
	{{if .GeoLocation.Coordinates}}
	<meta name="geo.position" content="{{.GeoLocation.Coordinates}}">
	{{end}}

	{{if .GeoLocation.PlaceName}}
	<meta name="geo.placename" content="{{.GeoLocation.PlaceName}}">
	{{end}}
	{{end}}

	<link rel="alternate" type="application/rss+xml" title="RSS" href="/rss.xml">

	<link rel="shortcut icon" href="/theme/favicon.ico" />

	<link rel="stylesheet" href="/theme/deck.css" media="screen">
	<link rel="stylesheet" href="/theme/screen.css" media="screen">
	<link rel="stylesheet" href="/theme/print.css" media="print">
	<link rel="stylesheet" href="/theme/codehighlighting/highlight.css" media="screen, print">

{{ if .ToplevelNavigation}}

	<form class="search" action="/search" method="GET">
		<input type="text" name="q" placeholder="search">
	</form>

	{{range .ToplevelNavigation.Entries}}

		{{.Title}}

	{{end}}

{{end}}

{{ if .BreadcrumbNavigation}}

	{{range .BreadcrumbNavigation.Entries}}

		{{.Title}}

	{{end}}

{{end}}

%s

Search

Tags

Sitemap

RSS Feed

>

`, ChildTemplatePlaceholder)
<commit_msg>Fixed the existing typehead functionality<commit_after>// Copyright 2013 Andreas Koch. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package templates

import (
	"fmt"
)

var masterTemplate = fmt.Sprintf(`<!DOCTYPE HTML>

	<meta charset="utf-8">
	<base href="{{ .BaseUrl }}">

	<title>{{.Title}}</title>

	<link rel="schema.DC" href="http://purl.org/dc/terms/">
	<meta name="DC.date" content="{{.CreationDate}}">

	{{if .GeoLocation }}
	{{if .GeoLocation.Coordinates}}
	<meta name="geo.position" content="{{.GeoLocation.Coordinates}}">
	{{end}}

	{{if .GeoLocation.PlaceName}}
	<meta name="geo.placename" content="{{.GeoLocation.PlaceName}}">
	{{end}}
	{{end}}

	<link rel="alternate" type="application/rss+xml" title="RSS" href="/rss.xml">

	<link rel="shortcut icon" href="/theme/favicon.ico" />

	<link rel="stylesheet" href="/theme/deck.css" media="screen">
	<link rel="stylesheet" href="/theme/screen.css" media="screen">
	<link rel="stylesheet" href="/theme/print.css" media="print">
	<link rel="stylesheet" href="/theme/codehighlighting/highlight.css" media="screen, print">

{{ if .ToplevelNavigation}}

	<form class="search" action="/search" method="GET">
		<input class="typeahead" type="text" name="q" placeholder="search">
	</form>

	{{range .ToplevelNavigation.Entries}}

		{{.Title}}

	{{end}}

{{end}}

{{ if .BreadcrumbNavigation}}

	{{range .BreadcrumbNavigation.Entries}}

		{{.Title}}

	{{end}}

{{end}}

%s

Search

Tags

Sitemap

RSS Feed

>

`, ChildTemplatePlaceholder)
<|endoftext|>


<commit_before>//go:build go1.18
// +build go1.18

package eventstreamapi

import "github.com/aws/aws-sdk-go/aws/request"

// This is a no-op for Go 1.18 and above.
func ApplyHTTPTransportFixes(r *request.Request) {
}
<commit_msg>eventstreamapi: fixup golint function docstring (#4290)<commit_after>//go:build go1.18
// +build go1.18

package eventstreamapi

import "github.com/aws/aws-sdk-go/aws/request"

// ApplyHTTPTransportFixes is a no-op for Go 1.18 and above.
func ApplyHTTPTransportFixes(r *request.Request) {
}
<|endoftext|>


<commit_before>package yaml

import (
	"testing"
	"bytes"
)

var parseTests = []struct {
	Input  string
	Output string
}{
	{
		Input:  "key1: val1\n",
		Output: "key1: val1\n",
	},
	{
		Input: "key: nest: val\n",
		Output: "key:\n" +
			"  nest: val\n",
	},
	{
		Input: "a: b: c: d\n" +
			"      e: f\n" +
			"   g: h: i\n" +
			"      j: k\n" +
			"# comment\n" +
			"   l: m\n" +
			"n: o\n" +
			"",
		Output: "n: o\n" +
			"a:\n" +
			"  l: m\n" +
			"  b:\n" +
			"    c: d\n" +
			"    e: f\n" +
			"  g:\n" +
			"    h: i\n" +
			"    j: k\n" +
			"",
	},
	{
		Input: "- item\n" +
			"",
		Output: "- item\n" +
			"",
	},
	{
		Input: "- item2\n" +
			"- item1\n" +
			"",
		Output: "- item2\n" +
			"- item1\n" +
			"",
	},
	{
		Input: "- - list1a\n" +
			"  - list1b\n" +
			"- - list2a\n" +
			"  - list2b\n" +
			"",
		Output: "- - list1a\n" +
			"  - list1b\n" +
			"- - list2a\n" +
			"  - list2b\n" +
			"",
	},
	{
		Input: "-   \n" +
			"  - - listA1a\n" +
			"    - listA1b\n" +
			"  - - listA2a\n" +
			"    - listA2b\n" +
			"-\n" +
			"  - - listB1a\n" +
			"    - listB1b\n" +
			"  - - listB2a\n" +
			"    - listB2b\n" +
			"",
		Output: "- - - listA1a\n" +
			"    - listA1b\n" +
			"  - - listA2a\n" +
			"    - listA2b\n" +
			"- - - listB1a\n" +
			"    - listB1b\n" +
			"  - - listB2a\n" +
			"    - listB2b\n" +
			"",
	},
	{
		Input: "  - keyA1a: aaa\n" +
			"    keyA1b: bbb\n" +
			"  - keyA2a: ccc\n" +
			"    keyA2b: ddd\n" +
			"  - keyB1a: eee\n" +
			"    keyB1b: fff\n" +
			"  - keyB2a: ggg\n" +
			"    keyB2b: hhh\n" +
			"",
		Output: "- keyA1a: aaa\n" +
			"  keyA1b: bbb\n" +
			"- keyA2a: ccc\n" +
			"  keyA2b: ddd\n" +
			"- keyB1a: eee\n" +
			"  keyB1b: fff\n" +
			"- keyB2a: ggg\n" +
			"  keyB2b: hhh\n" +
			"",
	},
	{
		Input: "japanese:\n" +
			" - ichi\n" +
			" - ni\n" +
			" - san\n" +
			"french:\n" +
			" - un\n" +
			" - deux\n" +
			" - trois\n" +
			"english:\n" +
			" - one\n" +
			" - two\n" +
			" - three\n" +
			"",
		Output: "english:\n" +
			"  - one\n" +
			"  - two\n" +
			"  - three\n" +
			"french:\n" +
			"  - un\n" +
			"  - deux\n" +
			"  - trois\n" +
			"japanese:\n" +
			"  - ichi\n" +
			"  - ni\n" +
			"  - san\n" +
			"",
	},
}

func TestParse(t *testing.T) {
	for idx, test := range parseTests {
		buf := bytes.NewBufferString(test.Input)
		node, err := Parse(buf)
		if err != nil {
			t.Errorf("parse: %s", err)
		}
		if got, want := Render(node), test.Output; got != want {
			t.Errorf("---%d---", idx)
			t.Errorf("got: %q:\n%s", got, got)
			t.Errorf("want: %q:\n%s", want, want)
		}
	}
}

var getTypeTests = []struct {
	Value string
	Type  int
	Split int
}{
	{
		Value: "a: b",
		Type:  typMapping,
		Split: 1,
	},
	{
		Value: "- b",
		Type:  typSequence,
		Split: 1,
	},
}

func TestGetType(t *testing.T) {
	for idx, test := range getTypeTests {
		v, s := getType([]byte(test.Value))
		if got, want := v, test.Type; got != want {
			t.Errorf("%d. type(%q) = %s, want %s", idx, test.Value,
				typNames[got], typNames[want])
		}
		if got, want := s, test.Split; got != want {
			got0, got1 := test.Value[:got], test.Value[got:]
			want0, want1 := test.Value[:want], test.Value[want:]
			t.Errorf("%d. split is %s|%s, want %s|%s", idx,
				got0, got1, want0, want1)
		}
	}
}
<commit_msg>Added some more blank line checks<commit_after>package yaml

import (
	"testing"
	"bytes"
)

var parseTests = []struct {
	Input  string
	Output string
}{
	{
		Input:  "key1: val1\n",
		Output: "key1: val1\n",
	},
	{
		Input: "key: nest: val\n",
		Output: "key:\n" +
			"  nest: val\n",
	},
	{
		Input: "a: b: c: d\n" +
			"      # comment\n" +
			"      e: f\n" +
			"   g: h: i\n" +
			"\n" +
			"      j: k\n" +
			"# comment\n" +
			"   l: m\n" +
			"n: o\n" +
			"",
		Output: "n: o\n" +
			"a:\n" +
			"  l: m\n" +
			"  b:\n" +
			"    c: d\n" +
			"    e: f\n" +
			"  g:\n" +
			"    h: i\n" +
			"    j: k\n" +
			"",
	},
	{
		Input: "- item\n" +
			"",
		Output: "- item\n" +
			"",
	},
	{
		Input: "- item2\n" +
			"- item1\n" +
			"",
		Output: "- item2\n" +
			"- item1\n" +
			"",
	},
	{
		Input: "- - list1a\n" +
			"  - list1b\n" +
			"- - list2a\n" +
			"  - list2b\n" +
			"",
		Output: "- - list1a\n" +
			"  - list1b\n" +
			"- - list2a\n" +
			"  - list2b\n" +
			"",
	},
	{
		Input: "-   \n" +
			"  - - listA1a\n" +
			"    - listA1b\n" +
			"  - - listA2a\n" +
			"    - listA2b\n" +
			"-\n" +
			"  - - listB1a\n" +
			"    - listB1b\n" +
			"  - - listB2a\n" +
			"    - listB2b\n" +
			"",
		Output: "- - - listA1a\n" +
			"    - listA1b\n" +
			"  - - listA2a\n" +
			"    - listA2b\n" +
			"- - - listB1a\n" +
			"    - listB1b\n" +
			"  - - listB2a\n" +
			"    - listB2b\n" +
			"",
	},
	{
		Input: "  - keyA1a: aaa\n" +
			"    keyA1b: bbb\n" +
			"  - keyA2a: ccc\n" +
			"    keyA2b: ddd\n" +
			"  - keyB1a: eee\n" +
			"    keyB1b: fff\n" +
			"  - keyB2a: ggg\n" +
			"    keyB2b: hhh\n" +
			"",
		Output: "- keyA1a: aaa\n" +
			"  keyA1b: bbb\n" +
			"- keyA2a: ccc\n" +
			"  keyA2b: ddd\n" +
			"- keyB1a: eee\n" +
			"  keyB1b: fff\n" +
			"- keyB2a: ggg\n" +
			"  keyB2b: hhh\n" +
			"",
	},
	{
		Input: "japanese:\n" +
			" - ichi\n" +
			" - ni\n" +
			" - san\n" +
			"french:\n" +
			" - un\n" +
			" - deux\n" +
			" - trois\n" +
			"english:\n" +
			" - one\n" +
			" - two\n" +
			" - three\n" +
			"",
		Output: "english:\n" +
			"  - one\n" +
			"  - two\n" +
			"  - three\n" +
			"french:\n" +
			"  - un\n" +
			"  - deux\n" +
			"  - trois\n" +
			"japanese:\n" +
			"  - ichi\n" +
			"  - ni\n" +
			"  - san\n" +
			"",
	},
}

func TestParse(t *testing.T) {
	for idx, test := range parseTests {
		buf := bytes.NewBufferString(test.Input)
		node, err := Parse(buf)
		if err != nil {
			t.Errorf("parse: %s", err)
		}
		if got, want := Render(node), test.Output; got != want {
			t.Errorf("---%d---", idx)
			t.Errorf("got: %q:\n%s", got, got)
			t.Errorf("want: %q:\n%s", want, want)
		}
	}
}

var getTypeTests = []struct {
	Value string
	Type  int
	Split int
}{
	{
		Value: "a: b",
		Type:  typMapping,
		Split: 1,
	},
	{
		Value: "- b",
		Type:  typSequence,
		Split: 1,
	},
}

func TestGetType(t *testing.T) {
	for idx, test := range getTypeTests {
		v, s := getType([]byte(test.Value))
		if got, want := v, test.Type; got != want {
			t.Errorf("%d. type(%q) = %s, want %s", idx, test.Value,
				typNames[got], typNames[want])
		}
		if got, want := s, test.Split; got != want {
			got0, got1 := test.Value[:got], test.Value[got:]
			want0, want1 := test.Value[:want], test.Value[want:]
			t.Errorf("%d. split is %s|%s, want %s|%s", idx,
				got0, got1, want0, want1)
		}
	}
}
<|endoftext|>


<commit_before>package yaml

import (
	"crypto/rsa"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"gopkg.in/yaml.v2"
)

type PkixData struct {
	CommonName       string `yaml:"commonname"`
	Country          string `yaml:"country"`
	Organization     string `yaml:"organization"`
	OrganizationUnit string `yaml:"organizationunit"`
}

type CertData struct {
	Id        string   `yaml:"id"`
	CA        bool     `yaml:"ca"`
	Parent    string   `yaml:"parent"`
	KeyType   string   `yaml:"keytype"`
	KeyLength int      `yaml:"keylength"`
	HashAlg   string   `yaml:"hashalg"`
	AltNames  []string `yaml:"altnames"`
	Pkix      PkixData `yaml:"pkix"`
}

type Cert struct {
	CertConfig   CertData `yaml:"certificate"`
	signed       bool
	toBeUsed     bool
	PrivateKey   rsa.PrivateKey
	CertTemplate x509.Certificate
	CertBytes    []byte
}

type Certs struct {
	Certificates []*Cert `yaml:"certificates"`
	Chain        map[string][]string
}

func Handler() {
	test := Certs{}
	data := ReadFile("./config/data.yaml")
	err := yaml.Unmarshal(data, &test)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	test.setupSigner()
	test.sign()
	//	fmt.Printf("--- test:\n%v\n\n", test)

}
func (c *Certs) setupSigner() {
	c.Chain = make(map[string][]string)
	for _, val := range c.Certificates {
		key := val.CertConfig.Parent
		id := val.CertConfig.Id
		if key == id {
			val.signed = true // perform selfSign
		} else if c.Chain[key] == nil {
			c.Chain[key] = []string{id}
		} else {
			c.Chain[key] = append(c.Chain[key], id)
		}
	}
}

func (c *Certs) sign() {
	for {
		sign := signers(c)
		if len(sign) == 0 {
			break
		}
		for _, s := range sign {
			list := c.Chain[s.CertConfig.Id]
			for _, certId := range list {
				fmt.Printf("%v is Sign: %s\n", s.CertConfig.Id, certId)
				for _, cert := range c.Certificates {
					if cert.CertConfig.Id == certId {
						// sign certificate method
						cert.signed = true
						break
					}
				}
			}
		}
	}
	for _, cert := range c.Certificates {
		if !cert.signed {
			fmt.Printf("Failed to sign: %s\n", cert.CertConfig.Id)
		}
	}
}

func signers(c *Certs) []*Cert {
	sign := []*Cert{}
	for _, val := range c.Certificates {
		if val.signed && !val.toBeUsed {
			sign = append(sign, val)
			val.toBeUsed = true
		}
	}
	return sign
}

func ReadFile(name string) []byte {
	data, err := ioutil.ReadFile(name)
	if err != nil {
		log.Println("Could not read file: %s\n", name)
		os.Exit(1)
	}
	return data
}
<commit_msg>save sign id for each certificate<commit_after>package yaml

import (
	"crypto/rsa"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"

	"gopkg.in/yaml.v2"
)

type PkixData struct {
	CommonName       string `yaml:"commonname"`
	Country          string `yaml:"country"`
	Organization     string `yaml:"organization"`
	OrganizationUnit string `yaml:"organizationunit"`
}

type CertData struct {
	Id        string   `yaml:"id"`
	CA        bool     `yaml:"ca"`
	Parent    string   `yaml:"parent"`
	KeyType   string   `yaml:"keytype"`
	KeyLength int      `yaml:"keylength"`
	HashAlg   string   `yaml:"hashalg"`
	AltNames  []string `yaml:"altnames"`
	Pkix      PkixData `yaml:"pkix"`
}

type Cert struct {
	CertConfig   CertData `yaml:"certificate"`
	signed       bool
	toBeUsed     bool
	PrivateKey   rsa.PrivateKey
	CertTemplate x509.Certificate
	CertBytes    []byte
	Signers      []string
}

type Certs struct {
	Certificates []*Cert `yaml:"certificates"`
	certSigners  map[string][]string
}

func Handler() {
	test := Certs{}
	data := ReadFile("./config/data.yaml")
	err := yaml.Unmarshal(data, &test)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	test.setupSigner()
	test.signAll()
	//	fmt.Printf("--- test:\n%v\n\n", test)

}
func (c *Certs) setupSigner() {
	c.certSigners = make(map[string][]string)
	for _, val := range c.Certificates {
		key := val.CertConfig.Parent
		id := val.CertConfig.Id
		if key == id {
			val.signed = true // perform selfSign
		} else if c.certSigners[key] == nil {
			c.certSigners[key] = []string{id}
		} else {
			c.certSigners[key] = append(c.certSigners[key], id)
		}
	}
}

func (c *Certs) signAll() {
	for {
		sign := findSigners(c)
		if len(sign) == 0 {
			break
		}
		for _, s := range sign {
			id := s.CertConfig.Id
			list := c.certSigners[id]
			for _, certId := range list {
				fmt.Printf("%v is Sign: %s\n", id, certId)
				for _, cert := range c.Certificates {
					if cert.CertConfig.Id == certId {
						// sign certificate method
						cert.signed = true
						if s.Signers == nil {
							cert.Signers = []string{id}
						} else {
							cert.Signers = append(s.Signers, id)
						}
						break
					}
				}
			}
		}
	}
	for _, cert := range c.Certificates {
		if len(cert.Signers) > 0 {
			fmt.Printf("Cert: %s, has certificate chain: %v\n", cert.CertConfig.Id, strings.Join(cert.Signers, ", "))
		}
		if !cert.signed {
			fmt.Printf("Failed to sign: %s\n", cert.CertConfig.Id)
		}
	}
}

func findSigners(c *Certs) []*Cert {
	sign := []*Cert{}
	for _, val := range c.Certificates {
		if val.signed && !val.toBeUsed {
			sign = append(sign, val)
			val.toBeUsed = true
		}
	}
	return sign
}

func ReadFile(name string) []byte {
	data, err := ioutil.ReadFile(name)
	if err != nil {
		log.Println("Could not read file: %s\n", name)
		os.Exit(1)
	}
	return data
}
<|endoftext|>


<commit_before>/*
Copyright 2017 The Kubernetes Authors.

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

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

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

// This file was automatically generated by informer-gen

package informers

import (
	runtime "k8s.io/apimachinery/pkg/runtime"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	apps "k8s.io/client-go/informers/apps"
	autoscaling "k8s.io/client-go/informers/autoscaling"
	batch "k8s.io/client-go/informers/batch"
	certificates "k8s.io/client-go/informers/certificates"
	core "k8s.io/client-go/informers/core"
	extensions "k8s.io/client-go/informers/extensions"
	internalinterfaces "k8s.io/client-go/informers/internalinterfaces"
	policy "k8s.io/client-go/informers/policy"
	rbac "k8s.io/client-go/informers/rbac"
	settings "k8s.io/client-go/informers/settings"
	storage "k8s.io/client-go/informers/storage"
	kubernetes "k8s.io/client-go/kubernetes"
	cache "k8s.io/client-go/tools/cache"
	reflect "reflect"
	sync "sync"
	time "time"
)

type sharedInformerFactory struct {
	client        kubernetes.Interface
	lock          sync.Mutex
	defaultResync time.Duration

	informers map[reflect.Type]cache.SharedIndexInformer
	// startedInformers is used for tracking which informers have been started.
	// This allows Start() to be called multiple times safely.
	startedInformers map[reflect.Type]bool
}

// NewSharedInformerFactory constructs a new instance of sharedInformerFactory
func NewSharedInformerFactory(client kubernetes.Interface, defaultResync time.Duration) SharedInformerFactory {
	return &sharedInformerFactory{
		client:           client,
		defaultResync:    defaultResync,
		informers:        make(map[reflect.Type]cache.SharedIndexInformer),
		startedInformers: make(map[reflect.Type]bool),
	}
}

// Start initializes all requested informers.
func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) {
	f.lock.Lock()
	defer f.lock.Unlock()

	for informerType, informer := range f.informers {
		if !f.startedInformers[informerType] {
			go informer.Run(stopCh)
			f.startedInformers[informerType] = true
		}
	}
}

// InternalInformerFor returns the SharedIndexInformer for obj using an internal
// client.
func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer {
	f.lock.Lock()
	defer f.lock.Unlock()

	informerType := reflect.TypeOf(obj)
	informer, exists := f.informers[informerType]
	if exists {
		return informer
	}
	informer = newFunc(f.client, f.defaultResync)
	f.informers[informerType] = informer

	return informer
}

// SharedInformerFactory provides shared informers for resources in all known
// API group versions.
type SharedInformerFactory interface {
	internalinterfaces.SharedInformerFactory
	ForResource(resource schema.GroupVersionResource) (GenericInformer, error)

	Apps() apps.Interface
	Autoscaling() autoscaling.Interface
	Batch() batch.Interface
	Certificates() certificates.Interface
	Core() core.Interface
	Extensions() extensions.Interface
	Policy() policy.Interface
	Rbac() rbac.Interface
	Settings() settings.Interface
	Storage() storage.Interface
}

func (f *sharedInformerFactory) Apps() apps.Interface {
	return apps.New(f)
}

func (f *sharedInformerFactory) Autoscaling() autoscaling.Interface {
	return autoscaling.New(f)
}

func (f *sharedInformerFactory) Batch() batch.Interface {
	return batch.New(f)
}

func (f *sharedInformerFactory) Certificates() certificates.Interface {
	return certificates.New(f)
}

func (f *sharedInformerFactory) Core() core.Interface {
	return core.New(f)
}

func (f *sharedInformerFactory) Extensions() extensions.Interface {
	return extensions.New(f)
}

func (f *sharedInformerFactory) Policy() policy.Interface {
	return policy.New(f)
}

func (f *sharedInformerFactory) Rbac() rbac.Interface {
	return rbac.New(f)
}

func (f *sharedInformerFactory) Settings() settings.Interface {
	return settings.New(f)
}

func (f *sharedInformerFactory) Storage() storage.Interface {
	return storage.New(f)
}
<commit_msg>generated client-go.<commit_after>/*
Copyright 2017 The Kubernetes Authors.

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

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

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

// This file was automatically generated by informer-gen

package informers

import (
	runtime "k8s.io/apimachinery/pkg/runtime"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	apps "k8s.io/client-go/informers/apps"
	autoscaling "k8s.io/client-go/informers/autoscaling"
	batch "k8s.io/client-go/informers/batch"
	certificates "k8s.io/client-go/informers/certificates"
	core "k8s.io/client-go/informers/core"
	extensions "k8s.io/client-go/informers/extensions"
	internalinterfaces "k8s.io/client-go/informers/internalinterfaces"
	policy "k8s.io/client-go/informers/policy"
	rbac "k8s.io/client-go/informers/rbac"
	settings "k8s.io/client-go/informers/settings"
	storage "k8s.io/client-go/informers/storage"
	kubernetes "k8s.io/client-go/kubernetes"
	cache "k8s.io/client-go/tools/cache"
	reflect "reflect"
	sync "sync"
	time "time"
)

type sharedInformerFactory struct {
	client        kubernetes.Interface
	lock          sync.Mutex
	defaultResync time.Duration

	informers map[reflect.Type]cache.SharedIndexInformer
	// startedInformers is used for tracking which informers have been started.
	// This allows Start() to be called multiple times safely.
	startedInformers map[reflect.Type]bool
}

// NewSharedInformerFactory constructs a new instance of sharedInformerFactory
func NewSharedInformerFactory(client kubernetes.Interface, defaultResync time.Duration) SharedInformerFactory {
	return &sharedInformerFactory{
		client:           client,
		defaultResync:    defaultResync,
		informers:        make(map[reflect.Type]cache.SharedIndexInformer),
		startedInformers: make(map[reflect.Type]bool),
	}
}

// Start initializes all requested informers.
func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) {
	f.lock.Lock()
	defer f.lock.Unlock()

	for informerType, informer := range f.informers {
		if !f.startedInformers[informerType] {
			go informer.Run(stopCh)
			f.startedInformers[informerType] = true
		}
	}
}

// WaitForCacheSync waits for all started informers' cache were synced.
func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool {
	informers := func() map[reflect.Type]cache.SharedIndexInformer {
		f.lock.Lock()
		defer f.lock.Unlock()

		informers := map[reflect.Type]cache.SharedIndexInformer{}
		for informerType, informer := range f.informers {
			if f.startedInformers[informerType] {
				informers[informerType] = informer
			}
		}
		return informers
	}()

	res := map[reflect.Type]bool{}
	for informType, informer := range informers {
		res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced)
	}
	return res
}

// InternalInformerFor returns the SharedIndexInformer for obj using an internal
// client.
func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer {
	f.lock.Lock()
	defer f.lock.Unlock()

	informerType := reflect.TypeOf(obj)
	informer, exists := f.informers[informerType]
	if exists {
		return informer
	}
	informer = newFunc(f.client, f.defaultResync)
	f.informers[informerType] = informer

	return informer
}

// SharedInformerFactory provides shared informers for resources in all known
// API group versions.
type SharedInformerFactory interface {
	internalinterfaces.SharedInformerFactory
	ForResource(resource schema.GroupVersionResource) (GenericInformer, error)
	WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool

	Apps() apps.Interface
	Autoscaling() autoscaling.Interface
	Batch() batch.Interface
	Certificates() certificates.Interface
	Core() core.Interface
	Extensions() extensions.Interface
	Policy() policy.Interface
	Rbac() rbac.Interface
	Settings() settings.Interface
	Storage() storage.Interface
}

func (f *sharedInformerFactory) Apps() apps.Interface {
	return apps.New(f)
}

func (f *sharedInformerFactory) Autoscaling() autoscaling.Interface {
	return autoscaling.New(f)
}

func (f *sharedInformerFactory) Batch() batch.Interface {
	return batch.New(f)
}

func (f *sharedInformerFactory) Certificates() certificates.Interface {
	return certificates.New(f)
}

func (f *sharedInformerFactory) Core() core.Interface {
	return core.New(f)
}

func (f *sharedInformerFactory) Extensions() extensions.Interface {
	return extensions.New(f)
}

func (f *sharedInformerFactory) Policy() policy.Interface {
	return policy.New(f)
}

func (f *sharedInformerFactory) Rbac() rbac.Interface {
	return rbac.New(f)
}

func (f *sharedInformerFactory) Settings() settings.Interface {
	return settings.New(f)
}

func (f *sharedInformerFactory) Storage() storage.Interface {
	return storage.New(f)
}
<|endoftext|>


<commit_before>package mqtt

import (
	"errors"
	"io"
	"log"
	"net"
	"sync"
	"time"
)

////////////////////Interface//////////////////////////////

type Provider interface {
	AddServerTransport(st ServerTransport)
	GetServerTransports() []ServerTransport
	RemoveServerTransport(st ServerTransport)

	AddListener(listener Listener)
	RemoveListener(listener Listener)

	CreateClientSession(ct ClientTransport) ClientSession
	GetClientSessions() []ClientSession
	DeleteClientSession(cs ClientSession)

	Forward(msg Message)
}

////////////////////Implementation////////////////////////

type provider struct {
	listeners        map[Listener]Listener
	serverTransports map[ServerTransport]ServerTransport
	clientSessions   map[ClientSession]*clientSession
	serverSessions   map[ServerSession]*serverSession

	waitGroup *sync.WaitGroup
}

func newProvider() *provider {
	this := &provider{}

	this.listeners = make(map[Listener]Listener)
	this.serverTransports = make(map[ServerTransport]ServerTransport)
	this.clientSessions = make(map[ClientSession]*clientSession)
	this.serverSessions = make(map[ServerSession]*serverSession)

	this.waitGroup = &sync.WaitGroup{}

	return this
}

func (this *provider) AddServerTransport(st ServerTransport) {
	this.serverTransports[st] = st
}

func (this *provider) GetServerTransports() []ServerTransport {
	serverTransports := make([]ServerTransport, len(this.serverTransports))

	l := 0
	for _, value := range this.serverTransports {
		serverTransports[l] = value
		l++
	}

	return serverTransports
}

func (this *provider) RemoveServerTransport(st ServerTransport) {
	delete(this.serverTransports, st)
}

func (this *provider) AddListener(l Listener) {
	this.listeners[l] = l
}

func (this *provider) RemoveListener(l Listener) {
	delete(this.listeners, l)
}

func (this *provider) CreateClientSession(ct ClientTransport) ClientSession {
	return nil
}

func (this *provider) GetClientSessions() []ClientSession {
	clientSessions := make([]ClientSession, len(this.clientSessions))

	l := 0
	for _, value := range this.clientSessions {
		clientSessions[l] = value
		l++
	}

	return clientSessions
}

func (this *provider) DeleteClientSession(cs ClientSession) {
	delete(this.clientSessions, cs)
}

func (this *provider) Run() {
	for _, st := range this.serverTransports {
		if err := st.Listen(); err != nil {
			log.Printf("Listening %s://%s:%d Failed!!!\n", st.GetNetwork(), st.GetAddress(), st.GetPort())
		} else {
			log.Printf("Listening %s://%s:%d Runing...\n", st.GetNetwork(), st.GetAddress(), st.GetPort())
			this.waitGroup.Add(1)
			go this.ServeAccept(st.(*transport))
		}
	}
}

func (this *provider) Stop() {
	for _, st := range this.serverTransports {
		st.Close()
	}
	for _, ss := range this.serverSessions {
		ss.Terminate(errors.New("Provider Stopped\n"))
	}
	this.waitGroup.Wait()
}

func (this *provider) ServeAccept(st *transport) {
	defer this.waitGroup.Done()
	for {
		select {
		case <-st.ch:
			log.Printf("Listening %s://%s:%d Stoped!!!\n", st.GetNetwork(), st.GetAddress(), st.GetPort())
			return
		default:
		}
		st.SetDeadline(time.Now().Add(1e9))
		conn, err := st.Accept()
		if err != nil {
			if opErr, ok := err.(*net.OpError); !(ok && opErr.Timeout()) {
				log.Println(err)
			}
			continue
		}
		this.waitGroup.Add(1)
		go this.ServeConn(conn)
	}
}

func (this *provider) ServeConn(conn net.Conn) {
	defer conn.Close()
	defer this.waitGroup.Done()

	ss := newServerSession(conn)
	this.serverSessions[ss] = ss

	var buf []byte
	var err error
	for {
		select {
		case <-ss.ch:
			log.Println("Disconnecting", conn.RemoteAddr())
			for _, ln := range this.listeners {
				ln.ProcessSessionTerminated(newEventSessionTerminated(ss, ss.Error()))
			}
			delete(this.serverSessions, ss)
			return
		default:
		}

		if buf, err = this.ReadPacket(conn); err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			} else if err != io.EOF {
				log.Println(err)
				for _, ln := range this.listeners {
					ln.ProcessIOException(newEventIOException(ss, conn.RemoteAddr()))
				}
			}
			ss.Terminate(err)
		} else {
			if evt := ss.Process(buf); evt != nil {
				switch evt.GetEventType() {
				case EVENT_CONNECT:
					for _, ln := range this.listeners {
						ln.ProcessConnect(evt.(EventConnect))
					}
				case EVENT_PUBLISH:
					for _, ln := range this.listeners {
						ln.ProcessPublish(evt.(EventPublish))
					}
				case EVENT_SUBSCRIBE:
					for _, ln := range this.listeners {
						ln.ProcessSubscribe(evt.(EventSubscribe))
					}
				case EVENT_UNSUBSCRIBE:
					for _, ln := range this.listeners {
						ln.ProcessUnsubscribe(evt.(EventUnsubscribe))
					}
				case EVENT_TIMEOUT:
					for _, ln := range this.listeners {
						ln.ProcessTimeout(evt.(EventTimeout))
					}
				case EVENT_IOEXCEPTION:
					for _, ln := range this.listeners {
						ln.ProcessIOException(evt.(EventIOException))
					}
					ss.Terminate(errors.New(ss.Error()))
				default:
					ss.Terminate(errors.New(ss.Error()))
				}
			}
		}
	}
}

func (this *provider) Forward(msg Message) {
	for _, ss := range this.serverSessions {
		if err := ss.Forward(msg); err != nil {
			log.Println(err)
			for _, ln := range this.listeners {
				ln.ProcessIOException(newEventIOException(ss, ss.conn.RemoteAddr()))
			}
		}
	}
}

func (this *provider) ReadPacket(conn net.Conn) ([]byte, error) {
	var pkt [1]byte
	var buf []byte
	var err error

	conn.SetDeadline(time.Now().Add(1e9))
	if _, err = conn.Read(pkt[:]); err != nil {
		return nil, err
	}
	buf = append(buf, pkt[0])

	var remainingLength uint32 = 0
	var multiplier uint32 = 1
	for {
		if _, err = conn.Read(pkt[:]); err != nil {
			return nil, err
		}
		buf = append(buf, pkt[0])
		remainingLength += uint32(pkt[0]&127) * multiplier
		if (pkt[0] & 128) == 0 {
			break
		}
		multiplier *= 128
	}

	if remainingLength > 0 {
		data := make([]byte, remainingLength)
		if _, err = io.ReadFull(conn, data); err != nil {
			return nil, err
		}
		buf = append(buf, data...)
	}

	return buf, nil
}
<commit_msg>fix provider EOF<commit_after>package mqtt

import (
	"errors"
	"io"
	"log"
	"net"
	"sync"
	"time"
)

////////////////////Interface//////////////////////////////

type Provider interface {
	AddServerTransport(st ServerTransport)
	GetServerTransports() []ServerTransport
	RemoveServerTransport(st ServerTransport)

	AddListener(listener Listener)
	RemoveListener(listener Listener)

	CreateClientSession(ct ClientTransport) ClientSession
	GetClientSessions() []ClientSession
	DeleteClientSession(cs ClientSession)

	Forward(msg Message)
}

////////////////////Implementation////////////////////////

type provider struct {
	listeners        map[Listener]Listener
	serverTransports map[ServerTransport]ServerTransport
	clientSessions   map[ClientSession]*clientSession
	serverSessions   map[ServerSession]*serverSession

	waitGroup *sync.WaitGroup
}

func newProvider() *provider {
	this := &provider{}

	this.listeners = make(map[Listener]Listener)
	this.serverTransports = make(map[ServerTransport]ServerTransport)
	this.clientSessions = make(map[ClientSession]*clientSession)
	this.serverSessions = make(map[ServerSession]*serverSession)

	this.waitGroup = &sync.WaitGroup{}

	return this
}

func (this *provider) AddServerTransport(st ServerTransport) {
	this.serverTransports[st] = st
}

func (this *provider) GetServerTransports() []ServerTransport {
	serverTransports := make([]ServerTransport, len(this.serverTransports))

	l := 0
	for _, value := range this.serverTransports {
		serverTransports[l] = value
		l++
	}

	return serverTransports
}

func (this *provider) RemoveServerTransport(st ServerTransport) {
	delete(this.serverTransports, st)
}

func (this *provider) AddListener(l Listener) {
	this.listeners[l] = l
}

func (this *provider) RemoveListener(l Listener) {
	delete(this.listeners, l)
}

func (this *provider) CreateClientSession(ct ClientTransport) ClientSession {
	return nil
}

func (this *provider) GetClientSessions() []ClientSession {
	clientSessions := make([]ClientSession, len(this.clientSessions))

	l := 0
	for _, value := range this.clientSessions {
		clientSessions[l] = value
		l++
	}

	return clientSessions
}

func (this *provider) DeleteClientSession(cs ClientSession) {
	delete(this.clientSessions, cs)
}

func (this *provider) Run() {
	for _, st := range this.serverTransports {
		if err := st.Listen(); err != nil {
			log.Printf("Listening %s://%s:%d Failed!!!\n", st.GetNetwork(), st.GetAddress(), st.GetPort())
		} else {
			log.Printf("Listening %s://%s:%d Runing...\n", st.GetNetwork(), st.GetAddress(), st.GetPort())
			this.waitGroup.Add(1)
			go this.ServeAccept(st.(*transport))
		}
	}
}

func (this *provider) Stop() {
	for _, st := range this.serverTransports {
		st.Close()
	}
	for _, ss := range this.serverSessions {
		ss.Terminate(errors.New("Provider Stopped\n"))
	}
	this.waitGroup.Wait()
}

func (this *provider) ServeAccept(st *transport) {
	defer this.waitGroup.Done()
	for {
		select {
		case <-st.ch:
			log.Printf("Listening %s://%s:%d Stoped!!!\n", st.GetNetwork(), st.GetAddress(), st.GetPort())
			return
		default:
		}
		st.SetDeadline(time.Now().Add(1e9))
		conn, err := st.Accept()
		if err != nil {
			if opErr, ok := err.(*net.OpError); !(ok && opErr.Timeout()) {
				log.Println(err)
			}
			continue
		}
		this.waitGroup.Add(1)
		go this.ServeConn(conn)
	}
}

func (this *provider) ServeConn(conn net.Conn) {
	defer conn.Close()
	defer this.waitGroup.Done()

	ss := newServerSession(conn)
	this.serverSessions[ss] = ss

	var buf []byte
	var err error
	for {
		select {
		case <-ss.ch:
			log.Println("Disconnecting", conn.RemoteAddr())
			for _, ln := range this.listeners {
				ln.ProcessSessionTerminated(newEventSessionTerminated(ss, ss.Error()))
			}
			delete(this.serverSessions, ss)
			return
		default:
		}

		if buf, err = this.ReadPacket(conn); err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Println(err)
			for _, ln := range this.listeners {
				ln.ProcessIOException(newEventIOException(ss, conn.RemoteAddr()))
			}
			ss.Terminate(err)
		} else {
			if evt := ss.Process(buf); evt != nil {
				switch evt.GetEventType() {
				case EVENT_CONNECT:
					for _, ln := range this.listeners {
						ln.ProcessConnect(evt.(EventConnect))
					}
				case EVENT_PUBLISH:
					for _, ln := range this.listeners {
						ln.ProcessPublish(evt.(EventPublish))
					}
				case EVENT_SUBSCRIBE:
					for _, ln := range this.listeners {
						ln.ProcessSubscribe(evt.(EventSubscribe))
					}
				case EVENT_UNSUBSCRIBE:
					for _, ln := range this.listeners {
						ln.ProcessUnsubscribe(evt.(EventUnsubscribe))
					}
				case EVENT_TIMEOUT:
					for _, ln := range this.listeners {
						ln.ProcessTimeout(evt.(EventTimeout))
					}
				case EVENT_IOEXCEPTION:
					for _, ln := range this.listeners {
						ln.ProcessIOException(evt.(EventIOException))
					}
					ss.Terminate(errors.New(ss.Error()))
				default:
					ss.Terminate(errors.New(ss.Error()))
				}
			}
		}
	}
}

func (this *provider) Forward(msg Message) {
	for _, ss := range this.serverSessions {
		if err := ss.Forward(msg); err != nil {
			log.Println(err)
			for _, ln := range this.listeners {
				ln.ProcessIOException(newEventIOException(ss, ss.conn.RemoteAddr()))
			}
		}
	}
}

func (this *provider) ReadPacket(conn net.Conn) ([]byte, error) {
	var pkt [1]byte
	var buf []byte
	var err error

	conn.SetDeadline(time.Now().Add(1e9))
	if _, err = conn.Read(pkt[:]); err != nil {
		return nil, err
	}
	buf = append(buf, pkt[0])

	var remainingLength uint32 = 0
	var multiplier uint32 = 1
	for {
		if _, err = conn.Read(pkt[:]); err != nil {
			return nil, err
		}
		buf = append(buf, pkt[0])
		remainingLength += uint32(pkt[0]&127) * multiplier
		if (pkt[0] & 128) == 0 {
			break
		}
		multiplier *= 128
	}

	if remainingLength > 0 {
		data := make([]byte, remainingLength)
		if _, err = io.ReadFull(conn, data); err != nil {
			return nil, err
		}
		buf = append(buf, data...)
	}

	return buf, nil
}
<|endoftext|>


<commit_before>package benchmarks

import (
	"runtime"
	"testing"

	"github.com/smartystreets/go-disruptor"
)

const singleWriterRingBufferSize = 1024 * 16

func BenchmarkSingleWriter(b *testing.B) {
	written, read := disruptor.NewCursor(), disruptor.NewCursor()
	reader := disruptor.NewReader(read, written, written)
	writer := disruptor.NewWriter(written, read, singleWriterRingBufferSize)

	iterations := int64(b.N)
	b.ReportAllocs()
	b.ResetTimer()

	go func() {
		for i := int64(0); i < iterations; i++ {
			if lower, upper := writer.Reserve(1); upper >= 0 {
				writer.Commit(lower, upper)
			}
		}
	}()

	for {
		_, upper := reader.Receive()
		if upper >= 0 {
			reader.Commit(upper)

			if upper+1 == iterations {
				break
			}
		}
	}
}

func init() {
	runtime.GOMAXPROCS(2)
}
<commit_msg>Added code to benchmark disruptor scenarios.<commit_after>package benchmarks

import (
	"math"
	"runtime"
	"testing"

	"github.com/smartystreets/go-disruptor"
)

const singleWriterRingBufferSize = 1024 * 16
const singleWriterRingBufferMask = singleWriterRingBufferSize - 1

func BenchmarkDisruptorWriterSingleClaim(b *testing.B) {
	benchmarkSingleWriter(b, 1)
}
func BenchmarkDisruptorWriterClaimMultiple(b *testing.B) {
	benchmarkSingleWriter(b, 32)
}

func benchmarkSingleWriter(b *testing.B, maxClaim int64) {
	written, read := disruptor.NewCursor(), disruptor.NewCursor()
	reader := disruptor.NewReader(read, written, written)
	writer := disruptor.NewWriter(written, read, singleWriterRingBufferSize)

	iterations := int64(b.N)
	ringBuffer := [singleWriterRingBufferSize]int64{}
	claim := (int64(math.Log2(float64(iterations))) + 1)
	if claim >= maxClaim {
		claim = maxClaim
	}

	b.ReportAllocs()
	b.ResetTimer()

	go func() {
		sequence := int64(0)
		for sequence < iterations {
			if lower, upper := writer.Reserve(claim); upper >= 0 {
				for ; sequence <= upper; sequence++ {
					ringBuffer[sequence&singleWriterRingBufferMask] = sequence
				}

				writer.Commit(lower, upper)
				sequence = upper
			}
		}
	}()

	sequence := int64(0)
	for sequence < iterations {
		if _, upper := reader.Receive(); upper >= 0 {
			for ; sequence <= upper; sequence++ {
				if sequence != ringBuffer[sequence&singleWriterRingBufferMask] {
					panic("Out of sequence")
				}
			}

			reader.Commit(upper)
			sequence = upper
		}
	}
}

func init() {
	runtime.GOMAXPROCS(2)
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"strings"
)

func ExtractColumn(logContents string, column uint8) string {
	var buffer bytes.Buffer
	lines := strings.Split(logContents, "\n")

	for i := range lines {
		cols := strings.Split(lines[i], " ")
		buffer.WriteString(cols[column])

		if column == 0 {
			buffer.WriteString(" ")
			buffer.WriteString(cols[1])
		}

		buffer.WriteString("\n")
	}

	return buffer.String()
}

func main() {
	var (
		column uint8
		buffer bytes.Buffer
	)

	_, err := fmt.Scan(&column)

	if err != nil {
		return
	}

	scanner := bufio.NewScanner(os.Stdin)

	for scanner.Scan() {
		buffer.WriteString(scanner.Text())
		buffer.WriteString("\n")
	}

	fmt.Printf(ExtractColumn(buffer.String(), column))
}
<commit_msg>fix: rewrote solution to the first ahomework assignment and it works now<commit_after>package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"strings"
)

func ExtractColumn(logContents string, column uint8) string {
	var buffer bytes.Buffer
	lines := strings.Split(logContents, "\n")

	for i := range lines {
        if lines[i] == "" {
            continue
        }

		cols := strings.Split(lines[i], " ")

		switch column {
		case 0:
			buffer.WriteString(cols[0])
			buffer.WriteString(" ")
			buffer.WriteString(cols[1])
		case 1:
			buffer.WriteString(cols[2])
		case 2:
			buffer.WriteString(cols[3])

			for j := 4; j < len(cols); j++ {
				buffer.WriteString(" ")
				buffer.WriteString(cols[j])
			}
		}

		buffer.WriteString("\n")
	}

	return buffer.String()
}

func main() {
	var (
		column uint8
		buffer bytes.Buffer
	)

	_, err := fmt.Scan(&column)

	if err != nil {
		return
	}

	scanner := bufio.NewScanner(os.Stdin)

	for scanner.Scan() {
		buffer.WriteString(scanner.Text())
		buffer.WriteString("\n")
	}

	fmt.Print(ExtractColumn(buffer.String(), column))
}
<|endoftext|>


<commit_before>package aks

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"regexp"
	"sort"

	"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2020-06-30/compute"
	"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-09-01/containerservice"
	"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2020-07-01/network"
	"github.com/Azure/azure-sdk-for-go/services/subscription/mgmt/2020-09-01/subscription"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/adal"
	"github.com/Azure/go-autorest/autorest/to"
	"github.com/mcuadros/go-version"
)

type virtualNetworksResponseBody struct {
	Name          string   `json:"name"`
	ResourceGroup string   `json:"resourceGroup"`
	Subnets       []subnet `json:"subnets"`
}

type subnet struct {
	Name         string `json:"name"`
	AddressRange string `json:"addressRange"`
}

var matchResourceGroup = regexp.MustCompile("/resource[gG]roups/(.+?)/")

func NewClientAuthorizer(cap *Capabilities) (autorest.Authorizer, error) {
	oauthConfig, err := adal.NewOAuthConfig(cap.AuthBaseURL, cap.TenantID)
	if err != nil {
		return nil, err
	}

	spToken, err := adal.NewServicePrincipalToken(*oauthConfig, cap.ClientID, cap.ClientSecret, cap.BaseURL)
	if err != nil {
		return nil, fmt.Errorf("couldn't authenticate to Azure cloud with error: %v", err)
	}

	return autorest.NewBearerAuthorizer(spToken), nil
}

func NewVirtualMachineClient(cap *Capabilities) (*compute.VirtualMachineSizesClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	virtualMachine := compute.NewVirtualMachineSizesClient(cap.SubscriptionID)
	virtualMachine.Authorizer = authorizer

	return &virtualMachine, nil
}

func NewContainerServiceClient(cap *Capabilities) (*containerservice.ContainerServicesClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	containerService := containerservice.NewContainerServicesClientWithBaseURI(cap.BaseURL, cap.SubscriptionID)
	containerService.Authorizer = authorizer

	return &containerService, nil
}

func NewNetworkServiceClient(cap *Capabilities) (*network.VirtualNetworksClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	containerService := network.NewVirtualNetworksClientWithBaseURI(cap.BaseURL, cap.SubscriptionID)
	containerService.Authorizer = authorizer

	return &containerService, nil
}

func NewClusterClient(cap *Capabilities) (*containerservice.ManagedClustersClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	client := containerservice.NewManagedClustersClientWithBaseURI(cap.BaseURL, cap.SubscriptionID)
	client.Authorizer = authorizer

	return &client, nil
}

func NewSubscriptionServiceClient(cap *Capabilities) (*subscription.SubscriptionsClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	subscriptionService := subscription.NewSubscriptionsClient()
	subscriptionService.Authorizer = authorizer

	return &subscriptionService, nil
}

type sortableVersion []string

func (s sortableVersion) Len() int {
	return len(s)
}

func (s sortableVersion) Swap(a, b int) {
	s[a], s[b] = s[b], s[a]
}

func (s sortableVersion) Less(a, b int) bool {
	return version.Compare(s[a], s[b], "<")
}

func listKubernetesVersions(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	if cap.ResourceLocation == "" {
		return nil, http.StatusBadRequest, fmt.Errorf("region is required")
	}

	clientContainer, err := NewContainerServiceClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}

	orchestrators, err := clientContainer.ListOrchestrators(ctx, cap.ResourceLocation, "managedClusters")
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get orchestrators: %v", err)
	}

	if orchestrators.Orchestrators == nil {
		return nil, http.StatusBadRequest, fmt.Errorf("no version profiles returned: %v", err)
	}

	var kubernetesVersions []string

	for _, profile := range *orchestrators.Orchestrators {
		if profile.OrchestratorType == nil || profile.OrchestratorVersion == nil {
			return nil, http.StatusInternalServerError, fmt.Errorf("unexpected nil orchestrator type or version")
		}

		if *profile.OrchestratorType == "Kubernetes" {
			kubernetesVersions = append(kubernetesVersions, *profile.OrchestratorVersion)
		}
	}

	sort.Sort(sortableVersion(kubernetesVersions))

	return encodeOutput(kubernetesVersions)
}

func listVirtualNetworks(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	clientNetwork, err := NewNetworkServiceClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}

	networkList, err := clientNetwork.ListAll(ctx)
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get networks: %v", err)
	}

	var networks []virtualNetworksResponseBody

	for networkList.NotDone() {
		var batch []virtualNetworksResponseBody

		for _, azureNetwork := range networkList.Values() {
			var subnets []subnet

			if azureNetwork.Subnets != nil {
				for _, azureSubnet := range *azureNetwork.Subnets {
					if azureSubnet.Name != nil {
						subnets = append(subnets, subnet{
							Name:         to.String(azureSubnet.Name),
							AddressRange: to.String(azureSubnet.AddressPrefix),
						})
					}
				}
			}

			if azureNetwork.ID == nil {
				return nil, http.StatusInternalServerError, fmt.Errorf("no ID on virtual network")
			}

			match := matchResourceGroup.FindStringSubmatch(*azureNetwork.ID)

			if len(match) < 2 || match[1] == "" {
				return nil, http.StatusInternalServerError, fmt.Errorf("could not parse virtual network ID")
			}

			if azureNetwork.Name == nil {
				return nil, http.StatusInternalServerError, fmt.Errorf("no name on virtual network")
			}

			batch = append(batch, virtualNetworksResponseBody{
				Name:          to.String(azureNetwork.Name),
				ResourceGroup: match[1],
				Subnets:       subnets,
			})
		}

		networks = append(networks, batch...)

		err = networkList.NextWithContext(ctx)
		if err != nil {
			return nil, http.StatusInternalServerError, err
		}
	}

	return encodeOutput(networks)
}

type clustersResponseBody struct {
	ResourceGroup string `json:"resourceGroup"`
	ClusterName   string `json:"clusterName"`
	RBACEnabled   bool   `json:"rbacEnabled"`
}

func listClusters(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	clientCluster, err := NewClusterClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}

	clusterList, err := clientCluster.List(ctx)
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get cluster list: %v", err)
	}

	var clusters []clustersResponseBody

	for clusterList.NotDone() {
		for _, cluster := range clusterList.Values() {
			tmpCluster := clustersResponseBody{
				ClusterName: to.String(cluster.Name),
				RBACEnabled: to.Bool(cluster.EnableRBAC),
			}
			if cluster.ID != nil {
				match := matchResourceGroup.FindStringSubmatch(to.String(cluster.ID))
				if len(match) < 2 || match[1] == "" {
					return nil, http.StatusInternalServerError, fmt.Errorf("could not parse virtual network ID")
				}
				tmpCluster.ResourceGroup = match[1]
			}
			clusters = append(clusters, tmpCluster)
		}

		err = clusterList.NextWithContext(ctx)
		if err != nil {
			return nil, http.StatusInternalServerError, err
		}
	}

	return encodeOutput(clusters)
}

func listVMSizes(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	if cap.ResourceLocation == "" {
		return nil, http.StatusBadRequest, fmt.Errorf("region is required")
	}

	virtualMachine, err := NewVirtualMachineClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}
	vmMachineSizeList, err := virtualMachine.List(ctx, cap.ResourceLocation)
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get VM sizes: %v", err)
	}

	vmSizes := make([]string, 0, len(*vmMachineSizeList.Value))

	for _, virtualMachineSize := range *vmMachineSizeList.Value {
		vmSizes = append(vmSizes, to.String(virtualMachineSize.Name))
	}

	return encodeOutput(vmSizes)
}

type locationsResponseBody struct {
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`
}

func listLocations(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	clientSubscription, err := NewSubscriptionServiceClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}
	locationList, err := clientSubscription.ListLocations(ctx, cap.SubscriptionID)
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get locations: %v", err)
	}

	var locations []locationsResponseBody

	for _, location := range *locationList.Value {
		locations = append(locations, locationsResponseBody{
			Name:        to.String(location.Name),
			DisplayName: to.String(location.DisplayName),
		})
	}

	return encodeOutput(locations)
}

func encodeOutput(result interface{}) ([]byte, int, error) {
	data, err := json.Marshal(&result)
	if err != nil {
		return data, http.StatusInternalServerError, err
	}

	return data, http.StatusOK, err
}
<commit_msg>Add Location to /meta/aksClusters list<commit_after>package aks

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"regexp"
	"sort"

	"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2020-06-30/compute"
	"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-09-01/containerservice"
	"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2020-07-01/network"
	"github.com/Azure/azure-sdk-for-go/services/subscription/mgmt/2020-09-01/subscription"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/adal"
	"github.com/Azure/go-autorest/autorest/to"
	"github.com/mcuadros/go-version"
)

type virtualNetworksResponseBody struct {
	Name          string   `json:"name"`
	ResourceGroup string   `json:"resourceGroup"`
	Subnets       []subnet `json:"subnets"`
}

type subnet struct {
	Name         string `json:"name"`
	AddressRange string `json:"addressRange"`
}

var matchResourceGroup = regexp.MustCompile("/resource[gG]roups/(.+?)/")

func NewClientAuthorizer(cap *Capabilities) (autorest.Authorizer, error) {
	oauthConfig, err := adal.NewOAuthConfig(cap.AuthBaseURL, cap.TenantID)
	if err != nil {
		return nil, err
	}

	spToken, err := adal.NewServicePrincipalToken(*oauthConfig, cap.ClientID, cap.ClientSecret, cap.BaseURL)
	if err != nil {
		return nil, fmt.Errorf("couldn't authenticate to Azure cloud with error: %v", err)
	}

	return autorest.NewBearerAuthorizer(spToken), nil
}

func NewVirtualMachineClient(cap *Capabilities) (*compute.VirtualMachineSizesClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	virtualMachine := compute.NewVirtualMachineSizesClient(cap.SubscriptionID)
	virtualMachine.Authorizer = authorizer

	return &virtualMachine, nil
}

func NewContainerServiceClient(cap *Capabilities) (*containerservice.ContainerServicesClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	containerService := containerservice.NewContainerServicesClientWithBaseURI(cap.BaseURL, cap.SubscriptionID)
	containerService.Authorizer = authorizer

	return &containerService, nil
}

func NewNetworkServiceClient(cap *Capabilities) (*network.VirtualNetworksClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	containerService := network.NewVirtualNetworksClientWithBaseURI(cap.BaseURL, cap.SubscriptionID)
	containerService.Authorizer = authorizer

	return &containerService, nil
}

func NewClusterClient(cap *Capabilities) (*containerservice.ManagedClustersClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	client := containerservice.NewManagedClustersClientWithBaseURI(cap.BaseURL, cap.SubscriptionID)
	client.Authorizer = authorizer

	return &client, nil
}

func NewSubscriptionServiceClient(cap *Capabilities) (*subscription.SubscriptionsClient, error) {
	authorizer, err := NewClientAuthorizer(cap)
	if err != nil {
		return nil, err
	}

	subscriptionService := subscription.NewSubscriptionsClient()
	subscriptionService.Authorizer = authorizer

	return &subscriptionService, nil
}

type sortableVersion []string

func (s sortableVersion) Len() int {
	return len(s)
}

func (s sortableVersion) Swap(a, b int) {
	s[a], s[b] = s[b], s[a]
}

func (s sortableVersion) Less(a, b int) bool {
	return version.Compare(s[a], s[b], "<")
}

func listKubernetesVersions(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	if cap.ResourceLocation == "" {
		return nil, http.StatusBadRequest, fmt.Errorf("region is required")
	}

	clientContainer, err := NewContainerServiceClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}

	orchestrators, err := clientContainer.ListOrchestrators(ctx, cap.ResourceLocation, "managedClusters")
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get orchestrators: %v", err)
	}

	if orchestrators.Orchestrators == nil {
		return nil, http.StatusBadRequest, fmt.Errorf("no version profiles returned: %v", err)
	}

	var kubernetesVersions []string

	for _, profile := range *orchestrators.Orchestrators {
		if profile.OrchestratorType == nil || profile.OrchestratorVersion == nil {
			return nil, http.StatusInternalServerError, fmt.Errorf("unexpected nil orchestrator type or version")
		}

		if *profile.OrchestratorType == "Kubernetes" {
			kubernetesVersions = append(kubernetesVersions, *profile.OrchestratorVersion)
		}
	}

	sort.Sort(sortableVersion(kubernetesVersions))

	return encodeOutput(kubernetesVersions)
}

func listVirtualNetworks(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	clientNetwork, err := NewNetworkServiceClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}

	networkList, err := clientNetwork.ListAll(ctx)
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get networks: %v", err)
	}

	var networks []virtualNetworksResponseBody

	for networkList.NotDone() {
		var batch []virtualNetworksResponseBody

		for _, azureNetwork := range networkList.Values() {
			var subnets []subnet

			if azureNetwork.Subnets != nil {
				for _, azureSubnet := range *azureNetwork.Subnets {
					if azureSubnet.Name != nil {
						subnets = append(subnets, subnet{
							Name:         to.String(azureSubnet.Name),
							AddressRange: to.String(azureSubnet.AddressPrefix),
						})
					}
				}
			}

			if azureNetwork.ID == nil {
				return nil, http.StatusInternalServerError, fmt.Errorf("no ID on virtual network")
			}

			match := matchResourceGroup.FindStringSubmatch(*azureNetwork.ID)

			if len(match) < 2 || match[1] == "" {
				return nil, http.StatusInternalServerError, fmt.Errorf("could not parse virtual network ID")
			}

			if azureNetwork.Name == nil {
				return nil, http.StatusInternalServerError, fmt.Errorf("no name on virtual network")
			}

			batch = append(batch, virtualNetworksResponseBody{
				Name:          to.String(azureNetwork.Name),
				ResourceGroup: match[1],
				Subnets:       subnets,
			})
		}

		networks = append(networks, batch...)

		err = networkList.NextWithContext(ctx)
		if err != nil {
			return nil, http.StatusInternalServerError, err
		}
	}

	return encodeOutput(networks)
}

type clustersResponseBody struct {
	ResourceGroup string `json:"resourceGroup"`
	ClusterName   string `json:"clusterName"`
	RBACEnabled   bool   `json:"rbacEnabled"`
	Location      string `json:"location"`
}

func listClusters(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	clientCluster, err := NewClusterClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}

	clusterList, err := clientCluster.List(ctx)
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get cluster list: %v", err)
	}

	var clusters []clustersResponseBody

	for clusterList.NotDone() {
		for _, cluster := range clusterList.Values() {
			tmpCluster := clustersResponseBody{
				ClusterName: to.String(cluster.Name),
				RBACEnabled: to.Bool(cluster.EnableRBAC),
				Location:    to.String(cluster.Location),
			}
			if cluster.ID != nil {
				match := matchResourceGroup.FindStringSubmatch(to.String(cluster.ID))
				if len(match) < 2 || match[1] == "" {
					return nil, http.StatusInternalServerError, fmt.Errorf("could not parse virtual network ID")
				}
				tmpCluster.ResourceGroup = match[1]
			}
			clusters = append(clusters, tmpCluster)
		}

		err = clusterList.NextWithContext(ctx)
		if err != nil {
			return nil, http.StatusInternalServerError, err
		}
	}

	return encodeOutput(clusters)
}

func listVMSizes(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	if cap.ResourceLocation == "" {
		return nil, http.StatusBadRequest, fmt.Errorf("region is required")
	}

	virtualMachine, err := NewVirtualMachineClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}
	vmMachineSizeList, err := virtualMachine.List(ctx, cap.ResourceLocation)
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get VM sizes: %v", err)
	}

	vmSizes := make([]string, 0, len(*vmMachineSizeList.Value))

	for _, virtualMachineSize := range *vmMachineSizeList.Value {
		vmSizes = append(vmSizes, to.String(virtualMachineSize.Name))
	}

	return encodeOutput(vmSizes)
}

type locationsResponseBody struct {
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`
}

func listLocations(ctx context.Context, cap *Capabilities) ([]byte, int, error) {
	clientSubscription, err := NewSubscriptionServiceClient(cap)
	if err != nil {
		return nil, http.StatusInternalServerError, err
	}
	locationList, err := clientSubscription.ListLocations(ctx, cap.SubscriptionID)
	if err != nil {
		return nil, http.StatusBadRequest, fmt.Errorf("failed to get locations: %v", err)
	}

	var locations []locationsResponseBody

	for _, location := range *locationList.Value {
		locations = append(locations, locationsResponseBody{
			Name:        to.String(location.Name),
			DisplayName: to.String(location.DisplayName),
		})
	}

	return encodeOutput(locations)
}

func encodeOutput(result interface{}) ([]byte, int, error) {
	data, err := json.Marshal(&result)
	if err != nil {
		return data, http.StatusInternalServerError, err
	}

	return data, http.StatusOK, err
}
<|endoftext|>


<commit_before>package v1alpha1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// ManagedCertificateList is a list of ManagedCertificate objects.
type ManagedCertificateList struct {
	metav1.TypeMeta `json:",inline"`
	// metdata is the standard list metadata.
	// +optional
	metav1.ListMeta `json:"metadata" protobuf:"bytes,1,opt,name=metadata"`

	// items is the list of managed certificate objects.
	Items []ManagedCertificate `json:"items" protobuf:"bytes,2,rep,name=items"`
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// ManagedCertificate configures for what domains the client requests managed certificate and with which Ingress they should be associated. It also provides the current status of the certficate.
type ManagedCertificate struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Specification of the managed certificate.
	// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status.
	// +optional
	Spec ManagedCertificateSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`

	// Current information about the managed certificate.
	// +optional
	Status ManagedCertificateStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

// ManagedCertificateSpec configures for what domains the client requests managed certificate and with which Ingress it should be associated.
type ManagedCertificateSpec struct {
	// Specifies a list of domains populated by the user for which he requests a managed certificate.
	Domains []string `json:"domains" protobuf:"bytes,2,rep,name=domains"`
}

// ManagedCertificateStatus provides the current state of the certificate.
type ManagedCertificateStatus struct {
	// Specifies the status of communication with backend (GCE) API.
	// +optional
	BackendStatus string `json:"backendStatus,omitempty" protobuf:"bytes,1,opt,name=backendStatus"`

	// Specifies the status of the managed certificate.
	// +optional
	CertificateStatus string `json:"certificateStatus,omitempty" protobuf:"bytes,2,opt,name=certificateStatus"`

	// Specifies the statuses of certificate provisioning for domains selected by the user.
	DomainStatus []DomainStatus `json:"domainStatus" protobuf:"bytes,3,rep,name=domainStatus"`

	// Specifies the name of the provisioned managed certificate.
	// +optional
	CertificateName string `json:"certificateName,omitempty" protobuf:"bytes,4,opt,name=certificateName"`
}

// DomainStatus is a pair which associates domain name with status of certificate provisioning for this domain.
type DomainStatus struct {
	// The domain name.
	Domain string `json:"domain" protobuf:"bytes,1,name=domain"`

	// The status.
	Status string `json:"status" protobuf:"bytes,2,name=status"`
}
<commit_msg>Updated crd api<commit_after>package v1alpha1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// ManagedCertificateList is a list of ManagedCertificate objects.
type ManagedCertificateList struct {
	metav1.TypeMeta `json:",inline"`
	// metdata is the standard list metadata.
	// +optional
	metav1.ListMeta `json:"metadata" protobuf:"bytes,1,opt,name=metadata"`

	// items is the list of managed certificate objects.
	Items []ManagedCertificate `json:"items" protobuf:"bytes,2,rep,name=items"`
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// ManagedCertificate configures for what domains the client requests managed certificate and with which Ingress they should be associated. It also provides the current status of the certficate.
type ManagedCertificate struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Specification of the managed certificate.
	// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status.
	// +optional
	Spec ManagedCertificateSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`

	// Current information about the managed certificate.
	// +optional
	Status ManagedCertificateStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

// ManagedCertificateSpec configures for what domains the client requests managed certificate and with which Ingress it should be associated.
type ManagedCertificateSpec struct {
	// Specifies a list of domains populated by the user for which he requests a managed certificate.
	Domains []string `json:"domains" protobuf:"bytes,2,rep,name=domains"`
}

// ManagedCertificateStatus provides the current state of the certificate.
type ManagedCertificateStatus struct {
	// Specifies the status of the managed certificate.
	// +optional
	CertificateStatus string `json:"certificateStatus,omitempty" protobuf:"bytes,2,opt,name=certificateStatus"`

	// Specifies the statuses of certificate provisioning for domains selected by the user.
	DomainStatus []DomainStatus `json:"domainStatus" protobuf:"bytes,3,rep,name=domainStatus"`

	// Specifies the name of the provisioned managed certificate.
	// +optional
	CertificateName string `json:"certificateName,omitempty" protobuf:"bytes,4,opt,name=certificateName"`
}

// DomainStatus is a pair which associates domain name with status of certificate provisioning for this domain.
type DomainStatus struct {
	// The domain name.
	Domain string `json:"domain" protobuf:"bytes,1,name=domain"`

	// The status.
	Status string `json:"status" protobuf:"bytes,2,name=status"`
}
<|endoftext|>


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

package driver

import (
	"encoding/json"
	"strings"
)

func BridgeCreate(ID string, domainid string, gatewayip string) {

	url := "/0/connectivity/domain/" + domainid + "/ne/bri" + ID
	data := []byte(`{"action": {
				"action1": {
					"action_text": "create_and_link_ifc(DYN_1)"}
				},
				"ifc": {},
				"mobility": "true",
				"ne_description": "PLUMgrid Bridge",
				"ne_dname": "net-` + ID[:10] + `",
				"ne_group": "Bridge",
				"ne_type": "bridge"
	}`)

	RestCall("PUT", url, data)

	url = "/0/connectivity/domain/" + domainid + "/rule_group/cnf" + ID
	data = []byte(`{"mark_disabled": false,
			"ne_dest": "/ne/bri` + ID + `/action/action1",
			"ne_dname": "cont-` + ID[10:] + `",
			"ne_type": "cnf-vmgroup",
					"rule": {
						"rules` + ID + `": {
							"add_context": "",
							"criteria": "pgtag2",
							"match": "bridge-` + ID[:10] + `"
						}
					}
	}`)

	RestCall("PUT", url, data)

	url = "/0/connectivity/domain_prop/" + domainid + "/ne/brii" + ID
	data = []byte(`{"ne_metadata": "` + gatewayip + `"}`)
	RestCall("PUT", url, data)
}

func BridgeDelete(ID string, domainid string) {

	url := "/0/connectivity/domain_prop/" + domainid + "/ne/brii" + ID
	RestCall("DELETE", url, nil)

	url = "/0/connectivity/domain/" + domainid + "/ne/bri" + ID
	RestCall("DELETE", url, nil)

	url = "/0/connectivity/domain/" + domainid + "/rule_group/cnf" + ID
	RestCall("DELETE", url, nil)
}

func FindDomainFromNetwork(ID string) (domainid string) {

	url := "/0/connectivity/domain?configonly=true&level=3"
	body, _ := RestCall("GET", url, nil)
	var domain_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_data)
	if err != nil {
		panic(err)
	}
	for domains, domain_val := range domain_data {
		if nes, ok := domain_val.(map[string]interface{})["ne"]; ok {
			if _, ok := nes.(map[string]interface{})["bri"+ID]; ok {
				domainid = domains
				break
			}
		}
	}
	return
}

func FindNetworkGateway(domainID string, networkID string) (gatewayIP string) {

	url := "/0/connectivity/domain_prop/" + domainID + "/ne/brii" + networkID
	body, _ := RestCall("GET", url, nil)
	var domain_prop map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_prop)
	if err != nil {
		panic(err)
	}
	gatewayIP = domain_prop["ne_metadata"].(string)
	return
}

func DomainCreate(domainID string) {

	url := "/0/connectivity/domain?configonly=true"
	body, _ := RestCall("GET", url, nil)
	var domain_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_data)
	if err != nil {
		panic(err)
	}
	for domains := range domain_data {
		if domains == domainID {
			return
		}
	}

	url = "/0/tenant_manager/tenants" + "/" + domainID
	data := []byte(`{"containers": {
				"` + domainID + `": {
					"enable": "True",
					"qos_marking": "9",
					"context": "` + domainID + `",
					"type": "Gold",
					"property": "Container ` + domainID + ` Property",
					"domains": {}, "rules": {}}}}`)

	RestCall("PUT", url, data)

	url = "/0/tunnel_service/vnd_config/" + domainID
	data = []byte(`{"profile_name": "VXLAN",
			"add_vlan": "False"}`)
	RestCall("PUT", url, data)

	url = "/0/connectivity/domain/" + domainID
	data = []byte(`{"container_group": "` + domainID + `",
			"topology_name": "docker"}`)
	RestCall("PUT", url, data)

	url = "/0/connectivity/domain_prop/" + domainID
	data = []byte(`{}`)
	RestCall("PUT", url, data)

	url = "/0/pem_master/log_rule/" + domainID
	data = []byte(`{"rule": {
				"rule_` + domainID + `": {
					"pgtag1": "` + domainID + `",
					"log_ifc_type": "ACCESS_VM"}}}`)

	RestCall("PUT", url, data)
}

func DomainDelete(domainID string) {

	url := "/0/connectivity/domain?configonly=true"
	body, _ := RestCall("GET", url, nil)
	var domain_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_data)
	if err != nil {
		panic(err)
	}
	for domains, domain_val := range domain_data {
		if domains == domainID {
			res := domain_val.(map[string]interface{})["ne"]
			if len(res.(map[string]interface{})) == 0 {

				url = "/0/pem_master/log_rule/" + domainID
				RestCall("DELETE", url, nil)

				url = "/0/connectivity/domain_prop/" + domainID
				RestCall("DELETE", url, nil)

				url = "/0/connectivity/domain/" + domainID
				RestCall("DELETE", url, nil)

				url = "/0/tunnel_service/vnd_config/" + domainID
				RestCall("DELETE", url, nil)

				url = "/0/tenant_manager/tenants" + "/" + domainID
				RestCall("DELETE", url, nil)
			}
		}
	}
}

func GetNeId(NeName string, DomainId string) (NeId string) {

	url := "/0/connectivity/domain/" + DomainId + "/ne?configonly=true&level=1"
	body, _ := RestCall("GET", url, nil)
	var ne_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &ne_data)
	if err != nil {
		panic(err)
	}
	for nes, ne_val := range ne_data {
		if ne_val.(map[string]interface{})["ne_dname"] == NeName {
			NeId = nes
			break
		}
	}
	return
}

func CreateRouterInterface(RouterName string, DomainId string, NetworkId string, IP string, Netmask string) {

	RouterId := GetNeId(RouterName, DomainId)
	CheckNeChildList(RouterId, DomainId, "ifc")
	CheckNeChildList(NetworkName(NetworkId), DomainId, "ifc")
	rtr_ifc := NetworkId
	url := "/0/connectivity/domain/" + DomainId + "/ne/" + RouterId + "/ifc/" + rtr_ifc
	data := []byte(`{"attachable": "true",
                         "list": "true",
                         "attach_type": "static,dynamic",
                         "mobility": "true",
                         "ifc_name": "` + rtr_ifc + `",
                         "ifc_type": "static",
                         "ip_address": "` + IP + `",
                         "ip_address_mask": "` + Netmask + `"}`)
	RestCall("PUT", url, data)

	net_ifc := RouterId
	url = "/0/connectivity/domain/" + DomainId + "/ne/" + NetworkName(NetworkId) + "/ifc/" + net_ifc
	data = []byte(`{"attachable": "true",
                         "list": "true",
                         "attach_type": "static,dynamic",
                         "mobility": "true",
                         "ifc_type": "static"}`)
	RestCall("PUT", url, data)

	link_name := RouterId + NetworkId
	url = "/0/connectivity/domain/" + DomainId + "/link/" + link_name
	data = []byte(`{"link_type": "static",
                         "link_name": "` + link_name + `",
                         "attachment1": "/ne/` + RouterId + `/ifc/` + rtr_ifc + `",
                         "attachment2": "/ne/` + NetworkName(NetworkId) + `/ifc/` + net_ifc + `"}`)
	RestCall("PUT", url, data)
}

func DeleteRouterInterface(DomainID string, NetworkID string) {

	var routerID string
	var links map[string]interface{}
	var ne_data map[string]interface{}
	url := "/0/connectivity/domain/" + DomainID
	body, _ := RestCall("GET", url, nil)
	var domain_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_data)
	if err != nil {
		panic(err)
	}
	for domains, domain_val := range domain_data {
		if domains == "link" {
			links = domain_val.(map[string]interface{})
		}
		if domains == "ne" {
			ne_data = domain_val.(map[string]interface{})
		}
	}

	if len(links) != 0 {
		for elem, _ := range links {
			if strings.HasSuffix(elem, NetworkID) {
				routerID = strings.Split(elem, NetworkID)[0]
			}
		}
	}
	if routerID != "" {
		for elem, _ := range ne_data {
			if elem == routerID {
				rtr_ifc := NetworkID
				ifc_url := url + "/ne/" + routerID + "/ifc/" + rtr_ifc
				RestCall("DELETE", ifc_url, nil)
			}
		}
	}
}

func NetworkName(ID string) (name string) {
	name = "bri" + ID
	return
}

func CheckNeChildList(NeId string, DomainId string, childList string) {

	url := "/0/connectivity/domain/" + DomainId + "/ne/" + NeId + "?configonly=true"
	body, _ := RestCall("GET", url, nil)
	var ne_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &ne_data)
	if err != nil {
		panic(err)
	}
	if _, ok := ne_data[childList]; ok {
		return
	} else {
		data := []byte(`{}`)
		RestCall("PUT", url+"/"+childList, data)
		return
	}
}
<commit_msg>improved router link delete<commit_after>// Copyright 2016 PLUMgrid
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.package main

package driver

import (
	"encoding/json"
	"strings"
)

func BridgeCreate(ID string, domainid string, gatewayip string) {

	url := "/0/connectivity/domain/" + domainid + "/ne/bri" + ID
	data := []byte(`{"action": {
				"action1": {
					"action_text": "create_and_link_ifc(DYN_1)"}
				},
				"ifc": {},
				"mobility": "true",
				"ne_description": "PLUMgrid Bridge",
				"ne_dname": "net-` + ID[:10] + `",
				"ne_group": "Bridge",
				"ne_type": "bridge"
	}`)

	RestCall("PUT", url, data)

	url = "/0/connectivity/domain/" + domainid + "/rule_group/cnf" + ID
	data = []byte(`{"mark_disabled": false,
			"ne_dest": "/ne/bri` + ID + `/action/action1",
			"ne_dname": "cont-` + ID[10:] + `",
			"ne_type": "cnf-vmgroup",
					"rule": {
						"rules` + ID + `": {
							"add_context": "",
							"criteria": "pgtag2",
							"match": "bridge-` + ID[:10] + `"
						}
					}
	}`)

	RestCall("PUT", url, data)

	url = "/0/connectivity/domain_prop/" + domainid + "/ne/brii" + ID
	data = []byte(`{"ne_metadata": "` + gatewayip + `"}`)
	RestCall("PUT", url, data)
}

func BridgeDelete(ID string, domainid string) {

	url := "/0/connectivity/domain_prop/" + domainid + "/ne/brii" + ID
	RestCall("DELETE", url, nil)

	url = "/0/connectivity/domain/" + domainid + "/ne/bri" + ID
	RestCall("DELETE", url, nil)

	url = "/0/connectivity/domain/" + domainid + "/rule_group/cnf" + ID
	RestCall("DELETE", url, nil)
}

func FindDomainFromNetwork(ID string) (domainid string) {

	url := "/0/connectivity/domain?configonly=true&level=3"
	body, _ := RestCall("GET", url, nil)
	var domain_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_data)
	if err != nil {
		panic(err)
	}
	for domains, domain_val := range domain_data {
		if nes, ok := domain_val.(map[string]interface{})["ne"]; ok {
			if _, ok := nes.(map[string]interface{})["bri"+ID]; ok {
				domainid = domains
				break
			}
		}
	}
	return
}

func FindNetworkGateway(domainID string, networkID string) (gatewayIP string) {

	url := "/0/connectivity/domain_prop/" + domainID + "/ne/brii" + networkID
	body, _ := RestCall("GET", url, nil)
	var domain_prop map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_prop)
	if err != nil {
		panic(err)
	}
	gatewayIP = domain_prop["ne_metadata"].(string)
	return
}

func DomainCreate(domainID string) {

	url := "/0/connectivity/domain?configonly=true"
	body, _ := RestCall("GET", url, nil)
	var domain_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_data)
	if err != nil {
		panic(err)
	}
	for domains := range domain_data {
		if domains == domainID {
			return
		}
	}

	url = "/0/tenant_manager/tenants" + "/" + domainID
	data := []byte(`{"containers": {
				"` + domainID + `": {
					"enable": "True",
					"qos_marking": "9",
					"context": "` + domainID + `",
					"type": "Gold",
					"property": "Container ` + domainID + ` Property",
					"domains": {}, "rules": {}}}}`)

	RestCall("PUT", url, data)

	url = "/0/tunnel_service/vnd_config/" + domainID
	data = []byte(`{"profile_name": "VXLAN",
			"add_vlan": "False"}`)
	RestCall("PUT", url, data)

	url = "/0/connectivity/domain/" + domainID
	data = []byte(`{"container_group": "` + domainID + `",
			"topology_name": "docker"}`)
	RestCall("PUT", url, data)

	url = "/0/connectivity/domain_prop/" + domainID
	data = []byte(`{}`)
	RestCall("PUT", url, data)

	url = "/0/pem_master/log_rule/" + domainID
	data = []byte(`{"rule": {
				"rule_` + domainID + `": {
					"pgtag1": "` + domainID + `",
					"log_ifc_type": "ACCESS_VM"}}}`)

	RestCall("PUT", url, data)
}

func DomainDelete(domainID string) {

	url := "/0/connectivity/domain?configonly=true"
	body, _ := RestCall("GET", url, nil)
	var domain_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_data)
	if err != nil {
		panic(err)
	}
	for domains, domain_val := range domain_data {
		if domains == domainID {
			res := domain_val.(map[string]interface{})["ne"]
			if len(res.(map[string]interface{})) == 0 {

				url = "/0/pem_master/log_rule/" + domainID
				RestCall("DELETE", url, nil)

				url = "/0/connectivity/domain_prop/" + domainID
				RestCall("DELETE", url, nil)

				url = "/0/connectivity/domain/" + domainID
				RestCall("DELETE", url, nil)

				url = "/0/tunnel_service/vnd_config/" + domainID
				RestCall("DELETE", url, nil)

				url = "/0/tenant_manager/tenants" + "/" + domainID
				RestCall("DELETE", url, nil)
			}
		}
	}
}

func GetNeId(NeName string, DomainId string) (NeId string) {

	url := "/0/connectivity/domain/" + DomainId + "/ne?configonly=true&level=1"
	body, _ := RestCall("GET", url, nil)
	var ne_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &ne_data)
	if err != nil {
		panic(err)
	}
	for nes, ne_val := range ne_data {
		if ne_val.(map[string]interface{})["ne_dname"] == NeName {
			NeId = nes
			break
		}
	}
	return
}

func CreateRouterInterface(RouterName string, DomainId string, NetworkId string, IP string, Netmask string) {

	RouterId := GetNeId(RouterName, DomainId)
	CheckNeChildList(RouterId, DomainId, "ifc")
	CheckNeChildList(NetworkName(NetworkId), DomainId, "ifc")
	rtr_ifc := NetworkId
	url := "/0/connectivity/domain/" + DomainId + "/ne/" + RouterId + "/ifc/" + rtr_ifc
	data := []byte(`{"attachable": "true",
                         "list": "true",
                         "attach_type": "static,dynamic",
                         "mobility": "true",
                         "ifc_name": "` + rtr_ifc + `",
                         "ifc_type": "static",
                         "ip_address": "` + IP + `",
                         "ip_address_mask": "` + Netmask + `"}`)
	RestCall("PUT", url, data)

	net_ifc := RouterId
	url = "/0/connectivity/domain/" + DomainId + "/ne/" + NetworkName(NetworkId) + "/ifc/" + net_ifc
	data = []byte(`{"attachable": "true",
                         "list": "true",
                         "attach_type": "static,dynamic",
                         "mobility": "true",
                         "ifc_type": "static"}`)
	RestCall("PUT", url, data)

	link_name := RouterId + NetworkId
	url = "/0/connectivity/domain/" + DomainId + "/link/" + link_name
	data = []byte(`{"link_type": "static",
                         "link_name": "` + link_name + `",
                         "attachment1": "/ne/` + RouterId + `/ifc/` + rtr_ifc + `",
                         "attachment2": "/ne/` + NetworkName(NetworkId) + `/ifc/` + net_ifc + `"}`)
	RestCall("PUT", url, data)
}

func DeleteRouterInterface(DomainID string, NetworkID string) {

	var routerID string
	var rtr_ifc string
	var links map[string]interface{}
	var ne_data map[string]interface{}
	url := "/0/connectivity/domain/" + DomainID
	body, _ := RestCall("GET", url, nil)
	var domain_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &domain_data)
	if err != nil {
		panic(err)
	}
	for domains, domain_val := range domain_data {
		if domains == "link" {
			links = domain_val.(map[string]interface{})
		}
		if domains == "ne" {
			ne_data = domain_val.(map[string]interface{})
		}
	}

	if len(links) != 0 {
		for att, att_info := range links {
			att_1 := att_info.(map[string]interface{})["attachment1"].(string)
			att_2 := att_info.(map[string]interface{})["attachment2"].(string)

			if strings.Split(att_1, "/")[2][3:] == NetworkID {
				routerID = strings.Split(att_2, "/")[2]
				rtr_ifc = strings.Split(att_2, "/")[4]
				RestCall("DELETE", url+"/link/"+att, nil)
			} else if strings.Split(att_2, "/")[2][3:] == NetworkID {
				routerID = strings.Split(att_1, "/")[2]
				rtr_ifc = strings.Split(att_1, "/")[4]
				RestCall("DELETE", url+"/link/"+att, nil)
			}
		}
	}
	if routerID != "" {
		for elem, _ := range ne_data {
			if elem == routerID {
				ifc_url := url + "/ne/" + routerID + "/ifc/" + rtr_ifc
				RestCall("DELETE", ifc_url, nil)
			}
		}
	}
}

func NetworkName(ID string) (name string) {
	name = "bri" + ID
	return
}

func CheckNeChildList(NeId string, DomainId string, childList string) {

	url := "/0/connectivity/domain/" + DomainId + "/ne/" + NeId + "?configonly=true"
	body, _ := RestCall("GET", url, nil)
	var ne_data map[string]interface{}
	err := json.Unmarshal([]byte(body), &ne_data)
	if err != nil {
		panic(err)
	}
	if _, ok := ne_data[childList]; ok {
		return
	} else {
		data := []byte(`{}`)
		RestCall("PUT", url+"/"+childList, data)
		return
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"net/http"
	"net/url"
	"os/exec"
	"strings"

	"github.com/docker/docker/api/types"
	"github.com/go-check/check"
)

func (s *DockerSuite) TestLegacyImages(c *check.C) {
	status, body, err := sockRequest("GET", "/v1.6/images/json", nil)
	c.Assert(status, check.Equals, http.StatusOK)
	c.Assert(err, check.IsNil)

	images := []types.LegacyImage{}
	if err = json.Unmarshal(body, &images); err != nil {
		c.Fatalf("Error on unmarshal: %s", err)
	}

	if len(images) == 0 || images[0].Tag == "" || images[0].Repository == "" {
		c.Fatalf("Bad data: %q", images)
	}
}

func (s *DockerSuite) TestApiImagesFilter(c *check.C) {
	name := "utest:tag1"
	name2 := "utest/docker:tag2"
	name3 := "utest:5000/docker:tag3"
	for _, n := range []string{name, name2, name3} {
		if out, err := exec.Command(dockerBinary, "tag", "busybox", n).CombinedOutput(); err != nil {
			c.Fatal(err, out)
		}
	}
	type image types.Image
	getImages := func(filter string) []image {
		v := url.Values{}
		v.Set("filter", filter)
		status, b, err := sockRequest("GET", "/images/json?"+v.Encode(), nil)
		c.Assert(status, check.Equals, http.StatusOK)
		c.Assert(err, check.IsNil)

		var images []image
		if err := json.Unmarshal(b, &images); err != nil {
			c.Fatal(err)
		}

		return images
	}

	errMsg := "incorrect number of matches returned"
	if images := getImages("utest*/*"); len(images[0].RepoTags) != 2 {
		c.Fatal(errMsg)
	}
	if images := getImages("utest"); len(images[0].RepoTags) != 1 {
		c.Fatal(errMsg)
	}
	if images := getImages("utest*"); len(images[0].RepoTags) != 1 {
		c.Fatal(errMsg)
	}
	if images := getImages("*5000*/*"); len(images[0].RepoTags) != 1 {
		c.Fatal(errMsg)
	}
}

func (s *DockerSuite) TestApiImagesSaveAndLoad(c *check.C) {
	testRequires(c, Network)
	out, err := buildImage("saveandload", "FROM hello-world\nENV FOO bar", false)
	if err != nil {
		c.Fatal(err)
	}
	id := strings.TrimSpace(out)

	res, body, err := sockRequestRaw("GET", "/images/"+id+"/get", nil, "")
	c.Assert(err, check.IsNil)
	c.Assert(res.StatusCode, check.Equals, http.StatusOK)

	defer body.Close()

	if out, err := exec.Command(dockerBinary, "rmi", id).CombinedOutput(); err != nil {
		c.Fatal(err, out)
	}

	res, loadBody, err := sockRequestRaw("POST", "/images/load", body, "application/x-tar")
	c.Assert(err, check.IsNil)
	c.Assert(res.StatusCode, check.Equals, http.StatusOK)

	defer loadBody.Close()

	inspectOut, err := exec.Command(dockerBinary, "inspect", "--format='{{ .Id }}'", id).CombinedOutput()
	if err != nil {
		c.Fatal(err, inspectOut)
	}
	if strings.TrimSpace(string(inspectOut)) != id {
		c.Fatal("load did not work properly")
	}
}

func (s *DockerSuite) TestApiImagesDelete(c *check.C) {
	testRequires(c, Network)
	name := "test-api-images-delete"
	out, err := buildImage(name, "FROM hello-world\nENV FOO bar", false)
	if err != nil {
		c.Fatal(err)
	}
	defer deleteImages(name)
	id := strings.TrimSpace(out)

	if out, err := exec.Command(dockerBinary, "tag", name, "test:tag1").CombinedOutput(); err != nil {
		c.Fatal(err, out)
	}

	status, _, err := sockRequest("DELETE", "/images/"+id, nil)
	c.Assert(status, check.Equals, http.StatusConflict)
	c.Assert(err, check.IsNil)

	status, _, err = sockRequest("DELETE", "/images/test:tag1", nil)
	c.Assert(status, check.Equals, http.StatusOK)
	c.Assert(err, check.IsNil)
}
<commit_msg>Adding test for "GET /images/(name)/history" API.<commit_after>package main

import (
	"encoding/json"
	"net/http"
	"net/url"
	"os/exec"
	"strings"

	"github.com/docker/docker/api/types"
	"github.com/go-check/check"
)

func (s *DockerSuite) TestLegacyImages(c *check.C) {
	status, body, err := sockRequest("GET", "/v1.6/images/json", nil)
	c.Assert(status, check.Equals, http.StatusOK)
	c.Assert(err, check.IsNil)

	images := []types.LegacyImage{}
	if err = json.Unmarshal(body, &images); err != nil {
		c.Fatalf("Error on unmarshal: %s", err)
	}

	if len(images) == 0 || images[0].Tag == "" || images[0].Repository == "" {
		c.Fatalf("Bad data: %q", images)
	}
}

func (s *DockerSuite) TestApiImagesFilter(c *check.C) {
	name := "utest:tag1"
	name2 := "utest/docker:tag2"
	name3 := "utest:5000/docker:tag3"
	for _, n := range []string{name, name2, name3} {
		if out, err := exec.Command(dockerBinary, "tag", "busybox", n).CombinedOutput(); err != nil {
			c.Fatal(err, out)
		}
	}
	type image types.Image
	getImages := func(filter string) []image {
		v := url.Values{}
		v.Set("filter", filter)
		status, b, err := sockRequest("GET", "/images/json?"+v.Encode(), nil)
		c.Assert(status, check.Equals, http.StatusOK)
		c.Assert(err, check.IsNil)

		var images []image
		if err := json.Unmarshal(b, &images); err != nil {
			c.Fatal(err)
		}

		return images
	}

	errMsg := "incorrect number of matches returned"
	if images := getImages("utest*/*"); len(images[0].RepoTags) != 2 {
		c.Fatal(errMsg)
	}
	if images := getImages("utest"); len(images[0].RepoTags) != 1 {
		c.Fatal(errMsg)
	}
	if images := getImages("utest*"); len(images[0].RepoTags) != 1 {
		c.Fatal(errMsg)
	}
	if images := getImages("*5000*/*"); len(images[0].RepoTags) != 1 {
		c.Fatal(errMsg)
	}
}

func (s *DockerSuite) TestApiImagesSaveAndLoad(c *check.C) {
	testRequires(c, Network)
	out, err := buildImage("saveandload", "FROM hello-world\nENV FOO bar", false)
	if err != nil {
		c.Fatal(err)
	}
	id := strings.TrimSpace(out)

	res, body, err := sockRequestRaw("GET", "/images/"+id+"/get", nil, "")
	c.Assert(err, check.IsNil)
	c.Assert(res.StatusCode, check.Equals, http.StatusOK)

	defer body.Close()

	if out, err := exec.Command(dockerBinary, "rmi", id).CombinedOutput(); err != nil {
		c.Fatal(err, out)
	}

	res, loadBody, err := sockRequestRaw("POST", "/images/load", body, "application/x-tar")
	c.Assert(err, check.IsNil)
	c.Assert(res.StatusCode, check.Equals, http.StatusOK)

	defer loadBody.Close()

	inspectOut, err := exec.Command(dockerBinary, "inspect", "--format='{{ .Id }}'", id).CombinedOutput()
	if err != nil {
		c.Fatal(err, inspectOut)
	}
	if strings.TrimSpace(string(inspectOut)) != id {
		c.Fatal("load did not work properly")
	}
}

func (s *DockerSuite) TestApiImagesDelete(c *check.C) {
	testRequires(c, Network)
	name := "test-api-images-delete"
	out, err := buildImage(name, "FROM hello-world\nENV FOO bar", false)
	if err != nil {
		c.Fatal(err)
	}
	defer deleteImages(name)
	id := strings.TrimSpace(out)

	if out, err := exec.Command(dockerBinary, "tag", name, "test:tag1").CombinedOutput(); err != nil {
		c.Fatal(err, out)
	}

	status, _, err := sockRequest("DELETE", "/images/"+id, nil)
	c.Assert(status, check.Equals, http.StatusConflict)
	c.Assert(err, check.IsNil)

	status, _, err = sockRequest("DELETE", "/images/test:tag1", nil)
	c.Assert(status, check.Equals, http.StatusOK)
	c.Assert(err, check.IsNil)
}

func (s *DockerSuite) TestApiImagesHistory(c *check.C) {
	testRequires(c, Network)
	name := "test-api-images-history"
	out, err := buildImage(name, "FROM hello-world\nENV FOO bar", false)
	c.Assert(err, check.IsNil)

	defer deleteImages(name)
	id := strings.TrimSpace(out)

	status, body, err := sockRequest("GET", "/images/"+id+"/history", nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusOK)

	var historydata []types.ImageHistory
	if err = json.Unmarshal(body, &historydata); err != nil {
		c.Fatalf("Error on unmarshal: %s", err)
	}

	c.Assert(len(historydata), check.Not(check.Equals), 0)
	c.Assert(historydata[0].Tags[0], check.Equals, "test-api-images-history:latest")
}
<|endoftext|>


<commit_before>package opentsdbclient

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
    "strconv"

	"github.com/cloudfoundry/sonde-go/events"
)

const DefaultAPIURL = "http://locahost/api"

type Client struct {
	apiURL       string
	metricPoints map[metricKey]metricValue
	prefix       string
}

func New(apiURL string, prefix string) *Client {
	return &Client{
		apiURL:       apiURL,
		metricPoints: make(map[metricKey]metricValue),
		prefix:       prefix,
	}
}

func (c *Client) AddMetric(envelope *events.Envelope) {
	key := metricKey{
		eventType:  envelope.GetEventType(),
		name:       getName(envelope),
		deployment: envelope.GetDeployment(),
		job:        envelope.GetJob(),
		index:      envelope.GetIndex(),
		ip:         envelope.GetIp(),
	}

	mVal := c.metricPoints[key]
	value := getValue(envelope)

	mVal.tags = getTags(envelope)
	mVal.points = append(mVal.points, point{
		timestamp: envelope.GetTimestamp() / int64(time.Second),
		value:     value,
	})

	c.metricPoints[key] = mVal
}

func (c *Client) PostMetrics() error {
	numMetrics := len(c.metricPoints)
	log.Printf("Posting %d metrics", numMetrics)
	url := c.seriesURL()
	seriesBytes := c.formatMetrics()
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(seriesBytes))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	if resp.StatusCode >= 300 || resp.StatusCode < 200 {
		return fmt.Errorf("opentsdb request returned HTTP status code: %v", resp.StatusCode)
	}

	c.metricPoints = make(map[metricKey]metricValue)
	return nil
}

func (c *Client) seriesURL() string {
	url := fmt.Sprintf("%s/put", c.apiURL)
	return url
}

func (c *Client) formatMetrics() []byte {
	metrics := []metric{}
	for key, mVal := range c.metricPoints {
  	for _, p := range mVal.points {
		  metrics = append(metrics, metric{
				Metric: c.prefix + key.name,
				Timestamp: p.timestamp,
				Value:   p.value,
				Tags:   mVal.tags,
     	})
    }
	}

	encodedMetric, _ := json.Marshal(metrics)

	return encodedMetric
}

type metricKey struct {
	eventType  events.Envelope_EventType
	name       string
	deployment string
	job        string
	index      string
	ip         string
}

type metricValue struct {
	tags   tags
	points []point
}

func getName(envelope *events.Envelope) string {
	switch envelope.GetEventType() {
	case events.Envelope_ValueMetric:
		return envelope.GetOrigin() + "." + envelope.GetValueMetric().GetName()
	case events.Envelope_CounterEvent:
		return envelope.GetOrigin() + "." + envelope.GetCounterEvent().GetName()
	default:
		return ""
	}
}

func getValue(envelope *events.Envelope) float64 {
	switch envelope.GetEventType() {
	case events.Envelope_ValueMetric:
		return envelope.GetValueMetric().GetValue()
	case events.Envelope_CounterEvent:
		return float64(envelope.GetCounterEvent().GetTotal())
	default:
		return 0
	}
}

func getTags(envelope *events.Envelope) tags {
    index, err := strconv.Atoi(envelope.GetIndex())
    if err != nil {
        fmt.Println("Error %s", err.Error())
        index = 0
    }
    fmt.Println("deployment %s, index %d", envelope.GetDeployment(), index)
    ret := tags{envelope.GetDeployment(), envelope.GetJob(), index, envelope.GetIp()}
    fmt.Println(ret)
    return ret
}

func appendTagIfNotEmpty(tags []string, key string, value string) []string {
	if value != "" {
		tags = append(tags, fmt.Sprintf("%s:%s", key, value))
	}
	return tags
}

type point struct {
	timestamp int64
	value     float64
}

func (p point) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`[%d, %f]`, p.timestamp, p.value)), nil
}

type metric struct {
	Metric string   `json:"metric"`
  Value  float64  `json:"value"`
  Timestamp int64 `json:"timestamp"`
	Host   string   `json:"host,omitempty"`
    Tags  tags `json:"tags"`
}

type tags struct {
    Deployment string `json:"deployment"`
    Job string `json:"job"`
    Index int `json:"index"`
    Ip string `json:"ip"`
}

type payload struct {
	Series []metric `json:"series"`
}
<commit_msg>[##100400046]fix timestamp error<commit_after>package opentsdbclient

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
    "strconv"

	"github.com/cloudfoundry/sonde-go/events"
)

const DefaultAPIURL = "http://locahost/api"

type Client struct {
	apiURL       string
	metricPoints map[metricKey]metricValue
	prefix       string
}

func New(apiURL string, prefix string) *Client {
	return &Client{
		apiURL:       apiURL,
		metricPoints: make(map[metricKey]metricValue),
		prefix:       prefix,
	}
}

func (c *Client) AddMetric(envelope *events.Envelope) {
	key := metricKey{
		eventType:  envelope.GetEventType(),
		name:       getName(envelope),
		deployment: envelope.GetDeployment(),
		job:        envelope.GetJob(),
		index:      envelope.GetIndex(),
		ip:         envelope.GetIp(),
	}

	mVal := c.metricPoints[key]
	value := getValue(envelope)

	mVal.tags = getTags(envelope)
	mVal.points = append(mVal.points, point{
		timestamp: envelope.GetTimestamp(),
		value:     value,
	})

	c.metricPoints[key] = mVal
}

func (c *Client) PostMetrics() error {
	numMetrics := len(c.metricPoints)
	log.Printf("Posting %d metrics", numMetrics)
	url := c.seriesURL()
	seriesBytes := c.formatMetrics()
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(seriesBytes))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	if resp.StatusCode >= 300 || resp.StatusCode < 200 {
		return fmt.Errorf("opentsdb request returned HTTP status code: %v", resp.StatusCode)
	}

	c.metricPoints = make(map[metricKey]metricValue)
	return nil
}

func (c *Client) seriesURL() string {
	url := fmt.Sprintf("%s/put", c.apiURL)
	return url
}

func (c *Client) formatMetrics() []byte {
	metrics := []metric{}
	for key, mVal := range c.metricPoints {
  	for _, p := range mVal.points {
		  metrics = append(metrics, metric{
				Metric: c.prefix + key.name,
				Timestamp: p.timestamp,
				Value:   p.value,
				Tags:   mVal.tags,
     	})
    }
	}

	encodedMetric, _ := json.Marshal(metrics)

	return encodedMetric
}

type metricKey struct {
	eventType  events.Envelope_EventType
	name       string
	deployment string
	job        string
	index      string
	ip         string
}

type metricValue struct {
	tags   tags
	points []point
}

func getName(envelope *events.Envelope) string {
	switch envelope.GetEventType() {
	case events.Envelope_ValueMetric:
		return envelope.GetOrigin() + "." + envelope.GetValueMetric().GetName()
	case events.Envelope_CounterEvent:
		return envelope.GetOrigin() + "." + envelope.GetCounterEvent().GetName()
	default:
		return ""
	}
}

func getValue(envelope *events.Envelope) float64 {
	switch envelope.GetEventType() {
	case events.Envelope_ValueMetric:
		return envelope.GetValueMetric().GetValue()
	case events.Envelope_CounterEvent:
		return float64(envelope.GetCounterEvent().GetTotal())
	default:
		return 0
	}
}

func getTags(envelope *events.Envelope) tags {
    index, err := strconv.Atoi(envelope.GetIndex())
    if err != nil {
        fmt.Println("Error %s", err.Error())
        index = 0
    }
    fmt.Println("deployment %s, index %d", envelope.GetDeployment(), index)
    ret := tags{envelope.GetDeployment(), envelope.GetJob(), index, envelope.GetIp()}
    fmt.Println(ret)
    return ret
}

func appendTagIfNotEmpty(tags []string, key string, value string) []string {
	if value != "" {
		tags = append(tags, fmt.Sprintf("%s:%s", key, value))
	}
	return tags
}

type point struct {
	timestamp int64
	value     float64
}

func (p point) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`[%d, %f]`, p.timestamp, p.value)), nil
}

type metric struct {
	Metric string   `json:"metric"`
  Value  float64  `json:"value"`
  Timestamp int64 `json:"timestamp"`
	Host   string   `json:"host,omitempty"`
    Tags  tags `json:"tags"`
}

type tags struct {
    Deployment string `json:"deployment"`
    Job string `json:"job"`
    Index int `json:"index"`
    Ip string `json:"ip"`
}

type payload struct {
	Series []metric `json:"series"`
}
<|endoftext|>