Top Banner
Go - Googles Sprache für skalierbare Systeme
73

Go - Googles Sprache für skalierbare Systeme

Aug 07, 2015

Download

Software

Frank Müller
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Go - Googles Sprache für skalierbare Systeme

Go - Googles Sprachefür skalierbare Systeme

Page 2: Go - Googles Sprache für skalierbare Systeme

Frank Müller

OldenburgBaujahr 1965

EntwicklerFachautor

[email protected]@themue

Page 3: Go - Googles Sprache für skalierbare Systeme

Parallelität oder Nebenläufigkeit?

Page 4: Go - Googles Sprache für skalierbare Systeme

❝ Parallelism Programming as the simultaneous

execution of (possibly related) computations.

Concurrency Programming as the composition

of independently executing processes.

Rob Pike

Page 5: Go - Googles Sprache für skalierbare Systeme

Sieh, wie wir dies nutzen ...

Page 6: Go - Googles Sprache für skalierbare Systeme

Bereitgestellte Infrastruktur ...

Page 7: Go - Googles Sprache für skalierbare Systeme

... ist nichts ohne bereitgestellte Dienste

Page 8: Go - Googles Sprache für skalierbare Systeme

mysql

wordpress

Bekanntes Szenario

auf individuellen

Servern

Page 9: Go - Googles Sprache für skalierbare Systeme

Höhere Komplexität in Clouds

wordpress

mediawikihaproxy-w mediawiki memcached

haproxy-b wordpress mysql

wordpressvarnish

Page 10: Go - Googles Sprache für skalierbare Systeme

Ein mühsamer Weg

Page 11: Go - Googles Sprache für skalierbare Systeme

Juju - Open Source Tool zur Automatisierung von Clouds

http://jujucharms.com

Page 12: Go - Googles Sprache für skalierbare Systeme

Plattformen

Page 13: Go - Googles Sprache für skalierbare Systeme

Plattformen

mediawiki

wordpress

AWS Azure OpenStack Joyent ...

haproxy-w mediawiki memcached

haproxy-b wordpress mysql

wordpressvarnish

Page 14: Go - Googles Sprache für skalierbare Systeme

juju generate-config juju bootstrap

Bootstrap

Page 15: Go - Googles Sprache für skalierbare Systeme

Bootstrap

API

State

Provisioner

...

Zentrale Funktionen

Page 16: Go - Googles Sprache für skalierbare Systeme

Provisionierung

Page 17: Go - Googles Sprache für skalierbare Systeme

juju deploy juju-gui juju deploy wordpress juju deploy mysql juju expose juju-gui

Bootstrap

juju-gui wordpress mysql

Page 18: Go - Googles Sprache für skalierbare Systeme

Relationen

Page 19: Go - Googles Sprache für skalierbare Systeme

juju add-relation wordpress mysql juju expose wordpress

Bootstrap

juju-gui wordpress mysql

Page 20: Go - Googles Sprache für skalierbare Systeme

Konfiguration

Page 21: Go - Googles Sprache für skalierbare Systeme

juju set mysql dataset-size=50% juju set wordpress tuning=optimized

Bootstrap

juju-gui wordpress* mysql*

Page 22: Go - Googles Sprache für skalierbare Systeme

Skalieren

Page 23: Go - Googles Sprache für skalierbare Systeme

juju deploy memcached juju add-relation wordpress memcached juju add-unit wordpress

wordpress*

Bootstrap

juju-gui wordpress* mysql*

memcached

Page 24: Go - Googles Sprache für skalierbare Systeme

Varianten

Page 25: Go - Googles Sprache für skalierbare Systeme

Unit

Unit

Unter- geordnete

Unit

Unit

Unit

Unit

ContainerDirekte AbhängigkeitStandard

Page 26: Go - Googles Sprache für skalierbare Systeme

Einige Charms

ceph

mediawiki mongodb

cassandra

rails

mysql

wordpress

rabbitmq

haproxy

apache2

hadoopsquid

hbase

couchdb

postgresqlnfsntp

Page 27: Go - Googles Sprache für skalierbare Systeme

Viel Spaß in den Wolken

Page 28: Go - Googles Sprache für skalierbare Systeme

Wie hilft uns Google Go hier?

Page 29: Go - Googles Sprache für skalierbare Systeme

Moderne Mehrkernsysteme sind wie die Vereinigung von Flüssen

Page 30: Go - Googles Sprache für skalierbare Systeme

Ihre Energie gilt eseffizient zu nutzen

Page 31: Go - Googles Sprache für skalierbare Systeme

Google Go als Multi-Paradigmen-Sprache

imperativ

bedingt funktional

bedingt objektorientiert

nebenläufig

Page 32: Go - Googles Sprache für skalierbare Systeme

❝It’s better to have apermanent income

than to befascinating.

Oscar Wilde

Page 33: Go - Googles Sprache für skalierbare Systeme

Nebenläufigkeit in Go

• Leichtgewichtige Goroutines im Thread Pool

• Sehr große Anzahl gleichzeitig möglich

• Kommunikation und Synchronisation über Channels

• Vielfältige Kontrolle durch select Statement

Page 34: Go - Googles Sprache für skalierbare Systeme

Kapselung in Typen

package service

type Service struct { thisChan chan *This thatChan chan *That foo bool bar int baz string }

Page 35: Go - Googles Sprache für skalierbare Systeme

Konstruktoren sind Funktionen

func NewService(...) *Service { s := &Service{ thisChan: make(chan *This), thatChan: make(chan *That, 10), …, }

// Start of the backend loop as goroutine. go s.loop()

return s }

Page 36: Go - Googles Sprache für skalierbare Systeme

Endlosschleifen und select

func (s *Service) loop() { ticker := time.NewTicker(time.Second) for { select { case this := <-s.thisChan: s.doThis(this) case that := <-s.thatChan: s.doThat(that) case <-ticker.C: s.doTick() } } }

Page 37: Go - Googles Sprache für skalierbare Systeme

Methoden als externe Schnittstellen

func (s *Service) DoThis(data string) int { respChan := make(chan int) this := &This{data, respChan}

s.thisChan <- this return <-respChan }

Page 38: Go - Googles Sprache für skalierbare Systeme

Beispiel: Goroutines als Server

Client

Client

Client

Server

Page 39: Go - Googles Sprache für skalierbare Systeme

Beispiel: Lastverteilung

Client

Client

Worker

Worker

Worker

Master

Page 40: Go - Googles Sprache für skalierbare Systeme

Netze von Goroutines

A C D

GFEB

E1 E2 E3

Page 41: Go - Googles Sprache für skalierbare Systeme

Goroutines können eigene Wegegehen …

Page 42: Go - Googles Sprache für skalierbare Systeme

… oder gemeinsame

Page 43: Go - Googles Sprache für skalierbare Systeme

Ein Wimmeln wie im Bienenstock

Page 44: Go - Googles Sprache für skalierbare Systeme

Einblicke in die Juju Architektur

Page 45: Go - Googles Sprache für skalierbare Systeme

State - Watcher - Worker

State

API Networker

Provisioner

Uniter

Deployer

...

!

Collections Individuelle Objekte

Lebenszyklen

Client

Page 46: Go - Googles Sprache für skalierbare Systeme

Lauter nebenläufige Arbeit

Agent

State

Worker

Goroutine

Goroutine

Worker

Goroutine

Goroutine

Worker

Goroutine

Goroutine

Page 47: Go - Googles Sprache für skalierbare Systeme

Beispiel Firewaller

unitd Loop

unitd Loop

machined Loop

State Main Loop

machined Loop

unitd Loop

serviced Loop

Environment Configuration

Machines

Machine Units

Exposes

Ports

Page 48: Go - Googles Sprache für skalierbare Systeme

Herausforderungen nebenläufiger Anwendungen

Rechenleistung nutzen

Rennen kontrollieren

Konflikte vermeiden

Probleme abfedern

Page 49: Go - Googles Sprache für skalierbare Systeme

Sehr naives Parallelisieren (1)

func process(in []int) []int { resultChan := make(chan int) for _, value := range in { // One goroutine per value. go processValue(value, resultChan) }

// Collecting the results. out := make([]int, len(in)) for i := 0; i < len(in); i++ { out[i] = <-resultChan } return out }

Page 50: Go - Googles Sprache für skalierbare Systeme

Sehr naives Parallelisieren (2)

func processValue( inValue int, resultChan chan int) { // Time of result calculation may vary. outValue := inValue …

resultChan <- outValue }

Page 51: Go - Googles Sprache für skalierbare Systeme

Problem und Verbesserung

• Unterschiedliche Laufzeiten führen zu falscher Indizierung im Ergebnis

• Index in der Verarbeitung mitführen

• Ergebnis gemäß Index setzen

Page 52: Go - Googles Sprache für skalierbare Systeme

Verbesserung (1)

func process(in []int) []int { resultChan := make(chan *result) for index, value := range in { // One goroutine per value. go processValue(index, value, resultChan) } out := make([]int, len(in)) for i := 0; i < len(in); i++ { result <- resultChan out[result.index] = result.value } return out }

Page 53: Go - Googles Sprache für skalierbare Systeme

Verbesserung (2)

type result struct { index int value int }

func processValue( index, inValue int, resultChan chan *result) { // Time of result calculation may vary. outValue := inValue …

// Send index with result. resultChan <- &result{index, outValue} }

Page 54: Go - Googles Sprache für skalierbare Systeme

Isolierung von Zugriffen

• Loops serialisieren Zugriffe

• Synchronisation über Channels oder Package sync

• Referenzen nur an eine Goroutine senden

• Aufteilung von Arrays und Slices

Page 55: Go - Googles Sprache für skalierbare Systeme

Arbeitsteilung (1)

// Process all data passed by reference. func process(ds []*Data) {

var wg sync.WaitGroup for i := 0; i < len(ds); i += chunkSize {

// Process one chunk in the background. go processChunk(ds[i:i+chunkSize], wg)

} // Wait for all processing to complete. wg.Wait()

}

Page 56: Go - Googles Sprache für skalierbare Systeme

Arbeitsteilung (2)

// Processing a chunk of data passed by reference. func processChunk(ds []*Data, wg sync.WaitGroup) {

// Increment WaitGroup counter and signal when done. wg.Add(1) defer wg.Done() // Process each data. for _, d := range ds {

if d != nil { // Direct manipulation. d.Foo = ... ...

} }

}

Page 57: Go - Googles Sprache für skalierbare Systeme

Kontrolle von Goroutines

• Keine direkte Beziehung zwischen Goroutines

• Kontrolle nur über Channels

• Externe Packages helfen

• gopkg.in/tomb.v2

• github.com/tideland/goas/v2/loop

Page 58: Go - Googles Sprache für skalierbare Systeme

Operation in einer Schleifefunc (t *T) loop() {

defer t.tomb.Done() for {

select { case <-t.tomb.Dying():

// Cleanup ... return

case f := <-t.fooChan: if err := t.foo(f); err != nil {

t.tomb.Kill(err) }

case b := <-t.barChan: // ...

} }

}

Page 59: Go - Googles Sprache für skalierbare Systeme

Steuerung von außen

// Stop ends the main loop. func (t *T) Stop() error {

// Kill(nil) means no error as reason. t.tomb.Kill(nil) return t.tomb.Wait()

}

// Err retrieves the error in case the backend loop died. func (t *T) Err() error {

return t.tomb.Err() }

Page 60: Go - Googles Sprache für skalierbare Systeme

Prüfung des Backends

func (t *T) Foo(foo *Foo) (*Bar, error) { env := &fooEnv{foo, make(chan *Bar)} select { case t.fooChan <- env: case <-t.tomb.Dead():

return nil, errors.New("backend dead") } select { case bar := <- env.barChan:

return bar, nil case <-t.tomb.Dead():

return nil, errors.New("backend dead") }

}

Page 61: Go - Googles Sprache für skalierbare Systeme

Schnittstellen

Page 62: Go - Googles Sprache für skalierbare Systeme

Flexible Nutzung

• Nur Deklaration

• Einbettung in umfassendere Interfaces

• Implizites Duck Typing

• Anwendbar auf jede Typdefination

Page 63: Go - Googles Sprache für skalierbare Systeme

Verhalten definieren und kombinieren

type StorageReader interface { Get(name string) (io.ReadCloser, error) List(prefix string) ([]string, error) URL(name string) (string, error)

}

type StorageWriter interface { Put(name string, r io.Reader, length int64) error Remove(name string) error

}

type Storage interface { StorageReader StorageWriter

}

Page 64: Go - Googles Sprache für skalierbare Systeme

Teilnutzung möglich

// Only the writing is needed. func Write(sw StorageWriter) error {

... return sw.Put(myName, myReader, myLen)

}

// Full storage access here. func RemoveFirst(s Storage, prefix string) error {

l, err := s.List(prefix) if err != nil { return err } return s.Remove(l[0])

}

Page 65: Go - Googles Sprache für skalierbare Systeme

Implementierung pro Provider

Environ

Storage Azure

AWS

MAAS

OpenStack

...

Page 66: Go - Googles Sprache für skalierbare Systeme

Vernetzung

Page 67: Go - Googles Sprache für skalierbare Systeme

Hilfreiche Packages

• net, …/http für IP und Web

• html/template, mime/… für Inhalte

• encoding/gob, …/json, …/xml für die Serialisierung

• compress/… zur Komprimierung

• crypto/… zur Verschlüsselung

Page 68: Go - Googles Sprache für skalierbare Systeme

Externe Packages von Google

• WebSocket, SPDY, Dict und mehr in golang.org/x/net

• Weitere Crypto Packages (u.a. OpenPGP) in golang.org/x/crypto

Page 69: Go - Googles Sprache für skalierbare Systeme

Serialisierung via JSON

type Parameters map[string]interface{}

type Action struct { Tag string `json:"tag"` Receiver string `json:"receiver"` Name string `json:"name"` Parameters Parameters `json:"parameters,omitempty"` }

Page 70: Go - Googles Sprache für skalierbare Systeme

Marshalling

action := Action{ Tag: "FooBar", … Paramaters: Parameters{"foo": 4711, "bar": true}, }

marshalledAction, err := json.Marshal(action) if err != nil { … }

n, err := anyWriter.Write(marshalledAction)

Page 71: Go - Googles Sprache für skalierbare Systeme

Unmarshalling

var action Action

err := json.Unmarshal(marshalledAction, &action) if err != nil { … }

fmt.Printf("Tag: %s\n", action.Tag)

Page 72: Go - Googles Sprache für skalierbare Systeme

API in Juju

Netz und Crypto

Reflection für Dispatching

WebSockets

Serialisierung via JSON

Page 73: Go - Googles Sprache für skalierbare Systeme

Bildquellen 123RFiStockphotoeigene Quellen