func (db *Database) StoreFileInfo(sample map[string]interface{}) (elastic.IndexResponse, error) {

	if len(db.Plugins) == 0 {
		return elastic.IndexResponse{}, errors.New("Database.Plugins is empty (you must set this field to use this function)")
	}

	// Test connection to ElasticSearch
	err := db.TestConnection()
	if err != nil {
		return elastic.IndexResponse{}, errors.Wrap(err, "failed to connect to database")
	}

	client, err := elastic.NewSimpleClient(
		elastic.SetURL(db.URL),
		elastic.SetBasicAuth(
			utils.Getopts(db.Username, "MALICE_ELASTICSEARCH_USERNAME", ""),
			utils.Getopts(db.Password, "MALICE_ELASTICSEARCH_PASSWORD", ""),
		),
	)
	if err != nil {
		return elastic.IndexResponse{}, errors.Wrap(err, "failed to create elasticsearch simple client")
	}

	// NOTE: I am not setting ID because I want to be able to re-scan files with updated signatures in the future
	fInfo := map[string]interface{}{
		// "id":      sample.SHA256,
		"file":      sample,
		"plugins":   db.Plugins,
		"scan_date": time.Now().Format(time.RFC3339Nano),
	}

	newScan, err := client.Index().
		Index(db.Index).
		Type(db.Type).
		OpType("index").
		// Id("1").
		BodyJson(fInfo).
		Do(context.Background())
	if err != nil {
		return elastic.IndexResponse{}, errors.Wrap(err, "failed to index file info")
	}

	log.WithFields(log.Fields{
		"id":    newScan.Id,
		"index": newScan.Index,
		"type":  newScan.Type,
	}).Debug("indexed sample")

	return *newScan, nil
}

// StoreFileInfo inserts initial sample info into database creating a placeholder for it


func (db *Database) StorePluginResults(results database.PluginResults) error {

	// Test connection to ElasticSearch
	err := db.TestConnection()
	if err != nil {
		return errors.Wrap(err, "failed to connect to database")
	}

	client, err := elastic.NewSimpleClient(
		elastic.SetURL(db.URL),
		elastic.SetBasicAuth(
			utils.Getopts(db.Username, "MALICE_ELASTICSEARCH_USERNAME", ""),
			utils.Getopts(db.Password, "MALICE_ELASTICSEARCH_PASSWORD", ""),
		),
	)
	if err != nil {
		return errors.Wrap(err, "failed to create elasticsearch simple client")
	}

	// get sample db record
	getSample, err := client.Get().
		Index(db.Index).
		Type(db.Type).
		Id(results.ID).
		Do(context.Background())
	// ignore 404 not found error
	if err != nil && !elastic.IsNotFound(err) {
		return errors.Wrapf(err, "failed to get sample with id: %s", results.ID)
	}

	if getSample != nil && getSample.Found {
		log.Debugf("got document %s in version %d from index %s, type %s\n", getSample.Id, getSample.Version, getSample.Index, getSample.Type)
		updateScan := map[string]interface{}{
			"scan_date": time.Now().Format(time.RFC3339Nano),
			"plugins": map[string]interface{}{
				results.Category: map[string]interface{}{
					results.Name: results.Data,
				},
			},
		}
		update, err := client.Update().Index(db.Index).Type(db.Type).Id(getSample.Id).
			Doc(updateScan).
			Do(context.Background())
		if err != nil {
			return errors.Wrapf(err, "failed to update sample with id: %s", results.ID)
		}

		log.Debugf("updated version of sample %q is now %d\n", update.Id, update.Version)

	} else {
		// ID not found so create new document with `index` command
		scan := map[string]interface{}{
			"plugins": map[string]interface{}{
				results.Category: map[string]interface{}{
					results.Name: results.Data,
				},
			},
			"scan_date": time.Now().Format(time.RFC3339Nano),
		}

		newScan, err := client.Index().
			Index(db.Index).
			Type(db.Type).
			OpType("index").
			// Id("1").
			BodyJson(scan).
			Do(context.Background())
		if err != nil {
			return errors.Wrapf(err, "failed to create new sample plugin doc with id: %s", results.ID)
		}

		log.WithFields(log.Fields{
			"id":    newScan.Id,
			"index": newScan.Index,
			"type":  newScan.Type,
		}).Debug("indexed sample")
	}

	return nil
}

// StorePluginResults stores a plugin's results in the database by updating
// the placeholder created by the call to StoreFileInfo

StorePluginResults stores a plugin s results in the database by updating the placeholder created by the call to StoreFileInfo


func CamelCase(src string) string {
	byteSrc := []byte(src)
	chunks := camelingRegex.FindAll(byteSrc, -1)
	for idx, val := range chunks {
		if idx > 0 {
			chunks[idx] = bytes.Title(val)
		}
	}
	return string(bytes.Join(chunks, nil))
}

func CamelCase ( src string ) string { byteSrc := [ ] byte ( src ) chunks := camelingRegex . FindAll ( byteSrc , - 1 ) for idx , val := range chunks { if idx > 0 { chunks [ idx ] = bytes . Title ( val ) } } return string ( bytes . Join ( chunks , nil ) ) }

// CamelCase converts strings to their camel case equivalent


func Getopt(name, dfault string) string {
	value := os.Getenv(name)
	if value == "" {
		value = dfault
	}
	return value
}

func Getopt ( name , dfault string ) string { value := os . Getenv ( name ) if value == " " { value = dfault } return value }

// Getopt reads environment variables.
// If not found will return a supplied default value

Getopt reads environment variables . If not found will return a supplied default value


func Getopts(userInput, envVar, dfault string) string {

	if len(strings.TrimSpace(userInput)) > 0 {
		return userInput
	}
	value := os.Getenv(envVar)
	if value == "" {
		value = dfault
	}
	return value
}

func Getopts ( userInput , envVar , dfault string ) string { if len ( strings . TrimSpace ( userInput ) ) > 0 { return userInput } value := os . Getenv ( envVar ) if value == " " { value = dfault } return value }

// Getopts reads from user input then environment variable and finally a sane default.

Getopts reads from user input then environment variable and finally a sane default .


func GetSHA256(name string) string {

	dat, err := ioutil.ReadFile(name)
	Assert(err)

	h256 := sha256.New()
	_, err = h256.Write(dat)
	Assert(err)

	return fmt.Sprintf("%x", h256.Sum(nil))
}

func GetSHA256 ( name string ) string { dat , err := ioutil . ReadFile ( name ) Assert ( err ) h256 := sha256 . New ( ) _ , err = h256 . Write ( dat ) Assert ( err ) return fmt . Sprintf ( " " , h256 . Sum ( nil ) ) }

// GetSHA256 calculates a file's sha256sum


func RunCommand(ctx context.Context, cmd string, args ...string) (string, error) {

	var c *exec.Cmd

	if ctx != nil {
		c = exec.CommandContext(ctx, cmd, args...)
	} else {
		c = exec.Command(cmd, args...)
	}

	output, err := c.Output()
	if err != nil {
		return string(output), err
	}

	// check for exec context timeout
	if ctx != nil {
		if ctx.Err() == context.DeadlineExceeded {
			return "", fmt.Errorf("command %s timed out", cmd)
		}
	}

	return string(output), nil
}

func
RunCommand
(
ctx
context
.
Context
,
cmd
string
,
args
...
string
)
(
string
,
error
)
{
var
c
*
exec
.
Cmd
if
ctx
!=
{
c
=
exec
.
CommandContext
(
ctx
,
cmd
,
args
...
)
}
else
{
c
=
exec
.
Command
(
cmd
,
args
...
)
}
output
,
err
:=
c
.
Output
(
)
if
err
!=
{
return
string
(
output
)
,
err
}
// check for exec context timeout
if
ctx
!=
{
if
ctx
.
Err
(
)
==
context
.
DeadlineExceeded
{
return
"
"
,
fmt
.
Errorf
(
"
"
,
cmd
)
}
}
return
string
(
output
)
,
}


func RemoveDuplicates(elements []string) []string {
	// Use map to record duplicates as we find them.
	encountered := map[string]bool{}
	result := []string{}

	for v := range elements {
		if encountered[elements[v]] == true {
			// Do not add duplicate.
		} else {
			// Record this element as an encountered element.
			encountered[elements[v]] = true
			// Append to result slice.
			result = append(result, elements[v])
		}
	}
	// Return the new slice.
	return result
}

// RemoveDuplicates removes duplicate items from a list


func Unzip(archive, target string) error {

	// fmt.Println("Unzip archive ", target)

	reader, err := zip.OpenReader(archive)
	if err != nil {
		return err
	}
	defer reader.Close()

	for _, file := range reader.File {
		filePath := filepath.Join(target, file.Name)

		if file.FileInfo().IsDir() {
			os.MkdirAll(filePath, file.Mode())
			continue
		}
		fileReader, err := file.Open()
		if err != nil {
			return err
		}
		defer fileReader.Close()

		targetFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
		if err != nil {
			return err
		}
		defer targetFile.Close()

		if _, err := io.Copy(targetFile, fileReader); err != nil {
			return err
		}
	}
	return nil
}

// Unzip unzips archive to target location


func SliceContainsString(a string, list []string) bool {
	for _, b := range list {
		if strings.Contains(b, a) {
			return true
		}
	}
	return false
}

func SliceContainsString ( a string , list [ ] string ) bool { for _ , b := range list { if strings . Contains ( b , a ) { return true } } return false }

// SliceContainsString returns if slice contains substring


func NewSMTP(filename string, environment string) (s *SMTP, err error) {
	conf, err := GetSMTP(filename, environment)
	if err != nil {
		return
	}
	auth := smtp.PlainAuth("", conf.Auth.User, conf.Auth.Password, conf.Host)
	f := smtp.SendMail
	if conf.SSL {
		f = SendMailSSL
	}
	s = &SMTP{auth: auth, send: f, addr: fmt.Sprintf("%s:%d", conf.Host, conf.Port)}
	return
}

func NewSMTP ( filename string , environment string ) ( s * SMTP , err error ) { conf , err := GetSMTP ( filename , environment ) if err != nil { return } auth := smtp . PlainAuth ( " " , conf . Auth . User , conf . Auth . Password , conf . Host ) f := smtp . SendMail if conf . SSL { f = SendMailSSL } s = & SMTP { auth : auth , send : f , addr : fmt . Sprintf ( " " , conf . Host , conf . Port ) } return }


func (s *SMTP) SendMail(from string, to []string, msg []byte) (err error) {
	err = s.send(s.addr, s.auth, from, to, msg)
	return
}

func ( s * SMTP ) SendMail ( from string , to [ ] string , msg [ ] byte ) ( err error ) { err = s . send ( s . addr , s . auth , from , to , msg ) return }


func (se *SMTPEnvironment) GetEnvironment(environment string) interface{} {
	for env, conf := range se.Env {
		if strings.Compare(environment, env) == 0 {
			return conf
		}
	}
	return nil
}

func ( se * SMTPEnvironment ) GetEnvironment ( environment string ) interface { } { for env , conf := range se . Env { if strings . Compare ( environment , env ) == 0 { return conf } } return nil }

//GetEnvironment returns a SMTP Server configuration for the specified environment in parameter


func GetSMTP(source interface{}, environment string) (smtp Config, err error) {
	var smtpEnvironment SMTPEnvironment
	i, err := config.Get(source, environment, &smtpEnvironment)
	smtp = i.(Config)
	return
}

func GetSMTP ( source interface { } , environment string ) ( smtp Config , err error ) { var smtpEnvironment SMTPEnvironment i , err := config . Get ( source , environment , & smtpEnvironment ) smtp = i . ( Config ) return }

//GetSMTP returns a SMTP Server configurations


func GetConfig(source interface{}, environment string) (server Config, err error) {
	var serverEnvironment ServerEnvironment
	i, err := config.Get(source, environment, &serverEnvironment)
	server = i.(Config)
	return
}

func GetConfig ( source interface { } , environment string ) ( server Config , err error ) { var serverEnvironment ServerEnvironment i , err := config . Get ( source , environment , & serverEnvironment ) server = i . ( Config ) return }

//GetConfig returns a Server configurations


func (m *Environment) GetEnvironment(environment string) interface{} {
	for env, conf := range m.Env {
		if strings.Compare(environment, env) == 0 {
			return conf
		}
	}
	return nil
}

func ( m * Environment ) GetEnvironment ( environment string ) interface { } { for env , conf := range m . Env { if strings . Compare ( environment , env ) == 0 { return conf } } return nil }

//GetEnvironment returns a Mongo configuration for the specified environment in parameter


func GetMongo(source interface{}, environment string) (mongo Config, err error) {
	var env Environment
	i, err := config.Get(source, environment, &env)
	mongo = i.(Config)
	return
}

func GetMongo ( source interface { } , environment string ) ( mongo Config , err error ) { var env Environment i , err := config . Get ( source , environment , & env ) mongo = i . ( Config ) return }

//GetMongo returns a Mongo configurations


func TokenHandler(next http.Handler, cnf web.Config) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token, err := request.ParseFromRequest(r, request.AuthorizationHeaderExtractor, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				//TODO: On ne passe jamais à l'intérieur
				return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
			}
			return []byte(cnf.Jwt.Key), nil
		})
		if err == nil && token.Valid {
			next.ServeHTTP(w, r)
		} else {
			if r.URL.String() == "/" {
				next.ServeHTTP(w, r)
			} else {
				w.WriteHeader(http.StatusUnauthorized)
			}
		}
	})
}


func (c *Conn) Receive() (*InMsg, error) {
	stanza, err := c.xmppConn.Recv()
	if err != nil {
		return nil, err
	}

	if c.debug {
		log.Printf("Incoming raw CCS stanza: %+v\n", stanza)
	}

	chat, ok := stanza.(xmpp.Chat)
	if !ok {
		return nil, nil
	}

	if chat.Type == "error" {
		// todo: once go-xmpp can parse XMPP error messages, return error with XMPP error message (issue: https://github.com/soygul/gcm/issues/14)
		return nil, errors.New("CCS returned an XMPP error (can be a stanza or JSON error or anything else)")
	}

	var m InMsg
	if err = json.Unmarshal([]byte(chat.Other[0]), &m); err != nil { // todo: handle other fields of chat (remote/type/text/other[1,2,..])
		return nil, errors.New("unknow message from CCS")
	}

	switch m.MessageType {
	case "ack":
		return &m, nil // todo: mark message as sent
	case "nack":
		return &m, nil // todo: try and resend the message (after reconnect if problem is about connection draining)
	case "receipt":
		return &m, nil // todo: mark message as delivered and remove from the queue
	case "control":
		return &m, nil // todo: handle connection draining (and any other control message type?)
	case "":
		// acknowledge the incoming ordinary messages as per spec
		ack := &OutMsg{MessageType: "ack", To: m.From, ID: m.ID}
		if _, err = c.Send(ack); err != nil {
			return nil, fmt.Errorf("failed to send ack message to CCS with error: %v", err)
		}
		return &m, nil
	default:
		// unknown message types can be ignored, as per GCM specs
	}
	return &m, nil
}

// Receive waits to receive the next incoming messages from the CCS connection.

Receive waits to receive the next incoming messages from the CCS connection .


func (c *Conn) Send(m *OutMsg) (n int, err error) {
	if m.ID == "" {
		if m.ID, err = getMsgID(); err != nil {
			return 0, err
		}
	}

	mb, err := json.Marshal(m)
	if err != nil {
		return 0, err
	}
	ms := string(mb)
	res := fmt.Sprintf(gcmMessageStanza, ms)
	return c.xmppConn.SendOrg(res)
}

func ( c * Conn ) Send ( m * OutMsg ) ( n int , err error ) { if m . ID == " " { if m . ID , err = getMsgID ( ) ; err != nil { return 0 , err } } mb , err := json . Marshal ( m ) if err != nil { return 0 , err } ms := string ( mb ) res := fmt . Sprintf ( gcmMessageStanza , ms ) return c . xmppConn . SendOrg ( res ) }

// Send sends a message to GCM CCS server and returns the number of bytes written and any error encountered.
// If empty message ID is given, it's auto-generated and message object is modified with the generated ID.

Send sends a message to GCM CCS server and returns the number of bytes written and any error encountered . If empty message ID is given it s auto - generated and message object is modified with the generated ID .


func (d pivnetReleaseDiffer) allBoshReleaseNames() []string {
	boshReleaseNamesMap := make(map[string]string)
	var addReleaseNames = func(br map[string]*release.BoshRelease) {
		for brname := range br {
			boshReleaseNamesMap[brname] = brname
		}
	}
	addReleaseNames(d.release1.BoshRelease)
	addReleaseNames(d.release2.BoshRelease)
	var releaseNames []string
	for brname := range boshReleaseNamesMap {
		releaseNames = append(releaseNames, brname)
	}
	return releaseNames
}

func ( d pivnetReleaseDiffer ) allBoshReleaseNames ( ) [ ] string { boshReleaseNamesMap := make ( map [ string ] string ) var addReleaseNames = func ( br map [ string ] * release . BoshRelease ) { for brname := range br { boshReleaseNamesMap [ brname ] = brname } } addReleaseNames ( d . release1 . BoshRelease ) addReleaseNames ( d . release2 . BoshRelease ) var releaseNames [ ] string for brname := range boshReleaseNamesMap { releaseNames = append ( releaseNames , brname ) } return releaseNames }

// allBoshReleaseNames returns a union of unique BOSH release names across all
// contained BOSH releases.

allBoshReleaseNames returns a union of unique BOSH release names across all contained BOSH releases .


func (dj *DeltaJob) AddedProperty(name string, p *enaml.JobManifestProperty) {
	dj.AddedProperties[name] = *p
}

func ( dj * DeltaJob ) AddedProperty ( name string , p * enaml . JobManifestProperty ) { dj . AddedProperties [ name ] = * p }

// AddedProperty adds a new "added" job property to the list of differences

AddedProperty adds a new added job property to the list of differences


func (dj *DeltaJob) RemovedProperty(name string, p *enaml.JobManifestProperty) {
	dj.RemovedProperties[name] = *p
}

func ( dj * DeltaJob ) RemovedProperty ( name string , p * enaml . JobManifestProperty ) { dj . RemovedProperties [ name ] = * p }

// RemovedProperty adds a new "removed" job property to the list of differences

RemovedProperty adds a new removed job property to the list of differences


func (r *Result) AddDeltaJob(dj *DeltaJob) {
	r.DeltaJob = append(r.DeltaJob, *dj)
}

func ( r * Result ) AddDeltaJob ( dj * DeltaJob ) { r . DeltaJob = append ( r . DeltaJob , * dj ) }

// AddDeltaJob adds a new delta for a specific job


func (r *Result) Concat(other *Result) {
	for _, dj := range other.DeltaJob {
		r.DeltaJob = append(r.DeltaJob, dj)
	}
}

func ( r * Result ) Concat ( other * Result ) { for _ , dj := range other . DeltaJob { r . DeltaJob = append ( r . DeltaJob , dj ) } }

// Concat adds the other result to this result


func (r *Release) Read(releaseLocation string) (io.ReadCloser, error) {
	local, err := r.Pull(releaseLocation)
	if err != nil {
		return nil, err
	}
	rr, err := os.Open(local)
	if err != nil {
		return nil, err
	}
	return rr, nil
}

func ( r * Release ) Read ( releaseLocation string ) ( io . ReadCloser , error ) { local , err := r . Pull ( releaseLocation ) if err != nil { return nil , err } rr , err := os . Open ( local ) if err != nil { return nil , err } return rr , nil }

// Read downloads the specified Release to the local cache dir and returns a
// reader to the underyling release package.

Read downloads the specified Release to the local cache dir and returns a reader to the underyling release package .


func (r *Release) Pull(releaseLocation string) (filename string, err error) {
	u, uerr := url.Parse(releaseLocation)
	if uerr != nil || !(u.Scheme == "http" || u.Scheme == "https") {
		// assume a local file, ensure it exists
		if _, ferr := os.Stat(releaseLocation); os.IsNotExist(ferr) {
			err = fmt.Errorf("Could not pull %s. The file doesn't exist or isn't a valid http(s) URL", releaseLocation)
			return
		}
		filename = releaseLocation
	} else {
		// remote file, ensure its in the local cache
		filename = r.CacheDir + "/" + path.Base(releaseLocation)
		if _, err = os.Stat(filename); os.IsNotExist(err) {
			fmt.Println("Could not find release in local cache. Downloading now.")
			err = r.download(releaseLocation, filename)
		}
	}
	return
}

// Pull downloads the specified Release to the local cache dir


func BuildJob(jobMeta BoshJobMeta, dest string) error {
	b, err := json.Marshal(jobMeta)

	if err != nil {
		return err
	}
	fmt.Println("building job: ", string(b))
	monitFile, specFile, err := createJobFiles(dest, jobMeta.Name)

	if err != nil {
		return err
	}
	defer monitFile.Close()
	defer specFile.Close()
	err = writeMonitFile(monitFile, jobMeta.Name, jobMeta.PIDFile)

	if err != nil {
		return err
	}
	err = writeSpecFile(specFile, jobMeta.Name, jobMeta.JobProperties, jobMeta.Packages)
	return err
}

func BuildJob ( jobMeta BoshJobMeta , dest string ) error { b , err := json . Marshal ( jobMeta ) if err != nil { return err } fmt . Println ( " " , string ( b ) ) monitFile , specFile , err := createJobFiles ( dest , jobMeta . Name ) if err != nil { return err } defer monitFile . Close ( ) defer specFile . Close ( ) err = writeMonitFile ( monitFile , jobMeta . Name , jobMeta . PIDFile ) if err != nil { return err } err = writeSpecFile ( specFile , jobMeta . Name , jobMeta . JobProperties , jobMeta . Packages ) return err }

//BuildJob - function to create a compiled version of the current job


func LoadBoshRelease(releaseRepo pull.Release, path string) (release *BoshRelease, err error) {
	var rr io.ReadCloser
	rr, err = releaseRepo.Read(path)
	if err != nil {
		return
	}
	defer func() {
		if cerr := rr.Close(); cerr != nil {
			err = cerr
		}
	}()
	release, err = readBoshRelease(rr)
	return
}

func LoadBoshRelease ( releaseRepo pull . Release , path string ) ( release * BoshRelease , err error ) { var rr io . ReadCloser rr , err = releaseRepo . Read ( path ) if err != nil { return } defer func ( ) { if cerr := rr . Close ( ) ; cerr != nil { err = cerr } } ( ) release , err = readBoshRelease ( rr ) return }

// LoadBoshRelease creates an initialized boshRelease instance from the
// specifed local or remote .tgz file

LoadBoshRelease creates an initialized boshRelease instance from the specifed local or remote . tgz file


func readBoshRelease(rr io.Reader) (*BoshRelease, error) {
	release := &BoshRelease{
		JobManifests: make(map[string]enaml.JobManifest),
	}
	err := release.readBoshRelease(rr)
	return release, err
}

func readBoshRelease ( rr io . Reader ) ( * BoshRelease , error ) { release := & BoshRelease { JobManifests : make ( map [ string ] enaml . JobManifest ) , } err := release . readBoshRelease ( rr ) return release , err }

// readBoshRelease creates an initialized boshRelease instance from the
// specifed .tgz reader

readBoshRelease creates an initialized boshRelease instance from the specifed . tgz reader


func (r *BoshRelease) readBoshRelease(rr io.Reader) error {
	w := pkg.NewTgzWalker(rr)
	w.OnMatch("release.MF", func(file pkg.FileEntry) error {
		return decodeYaml(file.Reader, &r.ReleaseManifest)
	})
	w.OnMatch("/jobs/", func(file pkg.FileEntry) error {
		job, jerr := r.readBoshJob(file.Reader)
		if jerr == nil {
			r.JobManifests[job.Name] = job
		}
		return jerr
	})
	err := w.Walk()
	return err
}

func ( r * BoshRelease ) readBoshRelease ( rr io . Reader ) error { w := pkg . NewTgzWalker ( rr ) w . OnMatch ( " " , func ( file pkg . FileEntry ) error { return decodeYaml ( file . Reader , & r . ReleaseManifest ) } ) w . OnMatch ( " " , func ( file pkg . FileEntry ) error { job , jerr := r . readBoshJob ( file . Reader ) if jerr == nil { r . JobManifests [ job . Name ] = job } return jerr } ) err := w . Walk ( ) return err }

// readBoshRelease reads a bosh release out of the given reader into a new
// boshRelease struct

readBoshRelease reads a bosh release out of the given reader into a new boshRelease struct


func (r *BoshRelease) readBoshJob(jr io.Reader) (enaml.JobManifest, error) {
	var job enaml.JobManifest
	jw := pkg.NewTgzWalker(jr)
	jw.OnMatch("job.MF", func(file pkg.FileEntry) error {
		return decodeYaml(file.Reader, &job)
	})
	err := jw.Walk()
	return job, err
}

func ( r * BoshRelease ) readBoshJob ( jr io . Reader ) ( enaml . JobManifest , error ) { var job enaml . JobManifest jw := pkg . NewTgzWalker ( jr ) jw . OnMatch ( " " , func ( file pkg . FileEntry ) error { return decodeYaml ( file . Reader , & job ) } ) err := jw . Walk ( ) return job , err }

// readBoshJob reads a BOSH job manifest out of the given reader into a new
// JobManifest struct

readBoshJob reads a BOSH job manifest out of the given reader into a new JobManifest struct


func (s *Client) NewRequest(method, url string, body io.Reader) (*http.Request, error) {
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}

	setAuth(s, req)
	return req, nil
}

func ( s * Client ) NewRequest ( method , url string , body io . Reader ) ( * http . Request , error ) { req , err := http . NewRequest ( method , url , body ) if err != nil { return nil , err } setAuth ( s , req ) return req , nil }

// NewRequest is like http.NewRequest, with the exception that it will add
// basic auth headers if the client is configured for basic auth.

NewRequest is like http . NewRequest with the exception that it will add basic auth headers if the client is configured for basic auth .


func (s *Client) PushCloudConfig(manifest []byte) error {
	ccm := enaml.NewCloudConfigManifest(manifest)
	req, err := s.newCloudConfigRequest(*ccm)
	if err != nil {
		return err
	}
	res, err := s.http.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	if res.StatusCode >= 400 {
		body, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return err
		}
		return fmt.Errorf("%s error pushing cloud config to BOSH: %s", res.Status, string(body))
	}
	return nil
}

func ( s * Client ) PushCloudConfig ( manifest [ ] byte ) error { ccm := enaml . NewCloudConfigManifest ( manifest ) req , err := s . newCloudConfigRequest ( * ccm ) if err != nil { return err } res , err := s . http . Do ( req ) if err != nil { return err } defer res . Body . Close ( ) if res . StatusCode >= 400 { body , err := ioutil . ReadAll ( res . Body ) if err != nil { return err } return fmt . Errorf ( " " , res . Status , string ( body ) ) } return nil }

// PushCloudConfig uploads a cloud config to bosh.

PushCloudConfig uploads a cloud config to bosh .


func Generate(packagename string, fileBytes []byte, outputDir string) {
	b := preprocessJobManifest(fileBytes)
	objects := make(map[string]map[string]ObjectField)
	var properties []string
	for _, v := range b.recs {
		properties = append(properties, v.Orig)
	}
	for i := 0; i < b.max; i++ {

		for _, v := range b.recs {
			if v.Length-1 >= i {

				var structname = v.StructName(i, packagename, properties)
				var typeName = v.TypeName(i, properties)
				elementName := v.Slice[i]
				attributeName := FormatName(elementName)

				if _, ok := objects[structname]; !ok {
					objects[structname] = make(map[string]ObjectField)
				}

				if previousElement, ok := objects[structname][attributeName]; !ok {
					lo.G.Debug("Adding", attributeName, "to", structname, "with type", typeName)
					objects[structname][attributeName] = ObjectField{
						ElementName:       attributeName,
						ElementType:       typeName,
						ElementAnnotation: createElementAnnotation(elementName),
						Meta:              v.Yaml,
					}
				} else {
					if previousElement.ElementAnnotation != createElementAnnotation(elementName) {
						lo.G.Warning("******** Recommended creating custom yaml marshaller on", structname, "for", attributeName, " ********")
						previousElement.ElementAnnotation = "`yaml:\"-\"`"
						objects[structname][attributeName] = previousElement
					}
				}
			}
		}
	}
	structs := generateStructs(objects, packagename)
	writeStructsToDisk(structs, outputDir)
}

func Generate ( packagename string , fileBytes [ ] byte , outputDir string ) { b := preprocessJobManifest ( fileBytes ) objects := make ( map [ string ] map [ string ] ObjectField ) var properties [ ] string for _ , v := range b . recs { properties = append ( properties , v . Orig ) } for i := 0 ; i < b . max ; i ++ { for _ , v := range b . recs { if v . Length - 1 >= i { var structname = v . StructName ( i , packagename , properties ) var typeName = v . TypeName ( i , properties ) elementName := v . Slice [ i ] attributeName := FormatName ( elementName ) if _ , ok := objects [ structname ] ; ! ok { objects [ structname ] = make ( map [ string ] ObjectField ) } if previousElement , ok := objects [ structname ] [ attributeName ] ; ! ok { lo . G . Debug ( " " , attributeName , " " , structname , " " , typeName ) objects [ structname ] [ attributeName ] = ObjectField { ElementName : attributeName , ElementType : typeName , ElementAnnotation : createElementAnnotation ( elementName ) , Meta : v . Yaml , } } else { if previousElement . ElementAnnotation != createElementAnnotation ( elementName ) { lo . G . Warning ( " " , structname , " " , attributeName , " " ) previousElement . ElementAnnotation = " \" \" " objects [ structname ] [ attributeName ] = previousElement } } } } } structs := generateStructs ( objects , packagename ) writeStructsToDisk ( structs , outputDir ) }

//Generate - used to generate a struct for a given job


func CreateNewRecord(property string, yaml enaml.JobManifestProperty) (record Record) {
	elementArray := strings.Split(property, ".")
	record = Record{
		Length: len(elementArray),
		Orig:   property,
		Slice:  elementArray,
		Yaml:   yaml,
	}
	return
}

func CreateNewRecord ( property string , yaml enaml . JobManifestProperty ) ( record Record ) { elementArray := strings . Split ( property , " " ) record = Record { Length : len ( elementArray ) , Orig : property , Slice : elementArray , Yaml : yaml , } return }

//CreateNewRecord - creates a record from a given period delimited property and enaml.JobManifestProperty

CreateNewRecord - creates a record from a given period delimited property and enaml . JobManifestProperty


func NewShowCmd(releaseRepo pull.Release, release string) *ShowCmd {
	return &ShowCmd{
		releaseRepo: releaseRepo,
		release:     release,
	}
}

func NewShowCmd ( releaseRepo pull . Release , release string ) * ShowCmd { return & ShowCmd { releaseRepo : releaseRepo , release : release , } }

// NewShowCmd creates a new ShowCmd instance.

NewShowCmd creates a new ShowCmd instance .


func (s *ShowCmd) All(w io.Writer) error {
	if filepath.Ext(s.release) == ".pivotal" {
		pivnetRelease, err := release.LoadPivnetRelease(s.releaseRepo, s.release)
		if err != nil {
			return err
		}
		for _, br := range pivnetRelease.BoshRelease {
			s.printBoshRelease(w, br)
		}
		return nil
	}
	boshRelease, err := release.LoadBoshRelease(s.releaseRepo, s.release)
	if err != nil {
		return err
	}
	s.printBoshRelease(w, boshRelease)
	return nil
}

func ( s * ShowCmd ) All ( w io . Writer ) error { if filepath . Ext ( s . release ) == " " { pivnetRelease , err := release . LoadPivnetRelease ( s . releaseRepo , s . release ) if err != nil { return err } for _ , br := range pivnetRelease . BoshRelease { s . printBoshRelease ( w , br ) } return nil } boshRelease , err := release . LoadBoshRelease ( s . releaseRepo , s . release ) if err != nil { return err } s . printBoshRelease ( w , boshRelease ) return nil }

// All writes out all the release data to writer.

All writes out all the release data to writer .


func (s *ConcoursePipeline) GetDefaultTaskImageResource() atc.ImageResource {
	return atc.ImageResource{
		Type: s.defaultImageType,
		Source: atc.Source{
			"repository": s.defaultImageRepository,
		},
	}
}

func ( s * ConcoursePipeline ) GetDefaultTaskImageResource ( ) atc . ImageResource { return atc . ImageResource { Type : s . defaultImageType , Source : atc . Source { " " : s . defaultImageRepository , } , } }

// GetDefaultTaskImageResource - convenience helper to output default object for
// task images

GetDefaultTaskImageResource - convenience helper to output default object for task images


func (s *ConcoursePipeline) AddRawJob(job atc.JobConfig) {
	s.Jobs = append(s.Jobs, job)
}

func ( s * ConcoursePipeline ) AddRawJob ( job atc . JobConfig ) { s . Jobs = append ( s . Jobs , job ) }

//AddRawJob helper to add a job to the pipeline manifest


func (s *ConcoursePipeline) AddGroup(name string, jobs ...string) {
	s.Groups = append(s.Groups, atc.GroupConfig{
		Name: name,
		Jobs: jobs,
	})
}

func ( s * ConcoursePipeline ) AddGroup ( name string , jobs ... string ) { s . Groups = append ( s . Groups , atc . GroupConfig { Name : name , Jobs : jobs , } ) }

//AddGroup helper to add a group to the pipeline manifest


func (s *ConcoursePipeline) GetResourceByName(name string) *atc.ResourceConfig {
	for i, v := range s.Resources {
		if v.Name == name {
			return &s.Resources[i]
		}
	}
	return nil
}

func ( s * ConcoursePipeline ) GetResourceByName ( name string ) * atc . ResourceConfig { for i , v := range s . Resources { if v . Name == name { return & s . Resources [ i ] } } return nil }

//GetResourceByName convenience method to find and return a resource by name


func (s *ConcoursePipeline) AddRawResource(rawResource atc.ResourceConfig) {
	s.Resources = append(s.Resources, rawResource)
}

func ( s * ConcoursePipeline ) AddRawResource ( rawResource atc . ResourceConfig ) { s . Resources = append ( s . Resources , rawResource ) }

//AddRawResource helper to add a resource to the pipeline manifest


func (s *ConcoursePipeline) AddResource(name string, typename string, source map[string]interface{}) {
	s.Resources = append(s.Resources, atc.ResourceConfig{
		Name:   name,
		Type:   typename,
		Source: source,
	})
}

func ( s * ConcoursePipeline ) AddResource ( name string , typename string , source map [ string ] interface { } ) { s . Resources = append ( s . Resources , atc . ResourceConfig { Name : name , Type : typename , Source : source , } ) }

//AddResource helper to add a resource to the pipeline manifest


func (s *ConcoursePipeline) AddGithubResource(name string, source map[string]interface{}) {
	s.AddResource(name, GithubResourceName, source)
}

func ( s * ConcoursePipeline ) AddGithubResource ( name string , source map [ string ] interface { } ) { s . AddResource ( name , GithubResourceName , source ) }

//AddGithubResource github specific resource add


func (s *ConcoursePipeline) AddBoshIOResource(name string, source map[string]interface{}) {
	s.AddResource(name, BoshIOResourceName, source)
}

func ( s * ConcoursePipeline ) AddBoshIOResource ( name string , source map [ string ] interface { } ) { s . AddResource ( name , BoshIOResourceName , source ) }

//AddBoshIOResource bosh io specific resource add


func (s *ConcoursePipeline) AddBoshDeploymentResource(name string, source map[string]interface{}) {
	s.AddResource(name, BoshDeploymentResourceName, source)
}

func ( s * ConcoursePipeline ) AddBoshDeploymentResource ( name string , source map [ string ] interface { } ) { s . AddResource ( name , BoshDeploymentResourceName , source ) }

//AddBoshDeploymentResource bosh deployment resource add


func (s *ConcoursePipeline) AddGitResource(name string, source map[string]interface{}) {
	s.AddResource(name, GitResourceName, source)
}

func ( s * ConcoursePipeline ) AddGitResource ( name string , source map [ string ] interface { } ) { s . AddResource ( name , GitResourceName , source ) }

//AddGitResource git specific resource add


func (d boshReleaseDiffer) allJobNames() []string {
	jobNamesMap := make(map[string]string)
	var addJobNames = func(br *release.BoshRelease) {
		if br != nil {
			for jbname := range br.JobManifests {
				jobNamesMap[jbname] = jbname
			}
		}
	}
	addJobNames(d.release1)
	addJobNames(d.release2)
	var jobNames []string
	for jname := range jobNamesMap {
		jobNames = append(jobNames, jname)
	}
	return jobNames
}

func ( d boshReleaseDiffer ) allJobNames ( ) [ ] string { jobNamesMap := make ( map [ string ] string ) var addJobNames = func ( br * release . BoshRelease ) { if br != nil { for jbname := range br . JobManifests { jobNamesMap [ jbname ] = jbname } } } addJobNames ( d . release1 ) addJobNames ( d . release2 ) var jobNames [ ] string for jname := range jobNamesMap { jobNames = append ( jobNames , jname ) } return jobNames }

// allJobNames returns a union of unique job names across both BOSH releases


func NewDeploymentManifestFromFile(f *os.File) *DeploymentManifest {
	var b []byte
	fi, _ := f.Stat()

	if fi.Size() > 0 {
		b, _ = ioutil.ReadAll(f)
	}
	return NewDeploymentManifest(b)
}

func NewDeploymentManifestFromFile ( f * os . File ) * DeploymentManifest { var b [ ] byte fi , _ := f . Stat ( ) if fi . Size ( ) > 0 { b , _ = ioutil . ReadAll ( f ) } return NewDeploymentManifest ( b ) }

//NewDeploymentManifestFromFile - will read any implementor of os.File and
//initialize a deployment manifest from its bytes.
//this can be used to read a file or os.Stdin

NewDeploymentManifestFromFile - will read any implementor of os . File and initialize a deployment manifest from its bytes . this can be used to read a file or os . Stdin


func NewDeploymentManifest(b []byte) *DeploymentManifest {
	dm := new(DeploymentManifest)
	yaml.Unmarshal(b, dm)
	return dm
}

func NewDeploymentManifest ( b [ ] byte ) * DeploymentManifest { dm := new ( DeploymentManifest ) yaml . Unmarshal ( b , dm ) return dm }

//NewDeploymentManifest - deployment manifest constructor


func (s *DeploymentManifest) AddRemoteRelease(releaseName, ver, url, sha1 string) (err error) {
	s.Releases = append(s.Releases, Release{
		Name:    releaseName,
		URL:     url,
		SHA1:    sha1,
		Version: ver,
	})
	return
}

func ( s * DeploymentManifest ) AddRemoteRelease ( releaseName , ver , url , sha1 string ) ( err error ) { s . Releases = append ( s . Releases , Release { Name : releaseName , URL : url , SHA1 : sha1 , Version : ver , } ) return }

//AddRemoteRelease - adds a remote release to the manifest. Url should not
//contain version information

AddRemoteRelease - adds a remote release to the manifest . Url should not contain version information


func (s *DeploymentManifest) AddRemoteStemcell(os, alias, ver, url, sha1 string) {
	s.Stemcells = append(s.Stemcells, Stemcell{
		OS:      os,
		Alias:   alias,
		Version: ver,
		URL:     url,
		SHA1:    sha1,
	})
}

func ( s * DeploymentManifest ) AddRemoteStemcell ( os , alias , ver , url , sha1 string ) { s . Stemcells = append ( s . Stemcells , Stemcell { OS : os , Alias : alias , Version : ver , URL : url , SHA1 : sha1 , } ) }

// AddRemoteStemcell adds a remote stemcell to the manifest.
// The URL should not contain version information.

AddRemoteStemcell adds a remote stemcell to the manifest . The URL should not contain version information .


func (s *DeploymentManifest) Tag(key string) string {
	if s.Tags == nil {
		return ""
	}
	return s.Tags[key]
}

func ( s * DeploymentManifest ) Tag ( key string ) string { if s . Tags == nil { return " " } return s . Tags [ key ] }

// Tag gets the tag value for a specified key.

Tag gets the tag value for a specified key .


func (s *DeploymentManifest) RemoveTag(key string) {
	if s.Tags != nil {
		delete(s.Tags, key)
	}
}

func ( s * DeploymentManifest ) RemoveTag ( key string ) { if s . Tags != nil { delete ( s . Tags , key ) } }

// RemoveTag removes the tag with the specified key.

RemoveTag removes the tag with the specified key .


func LoadPivnetRelease(releaseRepo pull.Release, path string) (release *PivnetRelease, err error) {
	release = &PivnetRelease{}
	var localPath string
	localPath, err = releaseRepo.Pull(path)
	if err != nil {
		return
	}
	release = &PivnetRelease{
		BoshRelease: make(map[string]*BoshRelease),
	}
	err = release.readPivnetRelease(localPath)
	return
}

func LoadPivnetRelease ( releaseRepo pull . Release , path string ) ( release * PivnetRelease , err error ) { release = & PivnetRelease { } var localPath string localPath , err = releaseRepo . Pull ( path ) if err != nil { return } release = & PivnetRelease { BoshRelease : make ( map [ string ] * BoshRelease ) , } err = release . readPivnetRelease ( localPath ) return }

// LoadPivnetRelease creates an initialized pivnetRelease instance from the
// specified .pivotal file.

LoadPivnetRelease creates an initialized pivnetRelease instance from the specified . pivotal file .


func (r *PivnetRelease) BoshReleaseOrEmpty(name string) *BoshRelease {
	br := r.BoshRelease[name]
	if br == nil {
		br = emptyBoshRelease
	}
	return br
}

func ( r * PivnetRelease ) BoshReleaseOrEmpty ( name string ) * BoshRelease { br := r . BoshRelease [ name ] if br == nil { br = emptyBoshRelease } return br }

// BoshReleaseOrEmpty returns the named BOSH release from this pivnet release
// if it exists, otherwise emptyBoshRelease is returned.

BoshReleaseOrEmpty returns the named BOSH release from this pivnet release if it exists otherwise emptyBoshRelease is returned .


func (r *PivnetRelease) readPivnetRelease(path string) error {
	walker := pkg.NewZipWalker(path)
	walker.OnMatch("releases/", func(file pkg.FileEntry) error {
		br, berr := readBoshRelease(file.Reader)
		if berr != nil {
			return berr
		}
		r.BoshRelease[br.ReleaseManifest.Name] = br
		return nil
	})
	return walker.Walk()
}

func ( r * PivnetRelease ) readPivnetRelease ( path string ) error { walker := pkg . NewZipWalker ( path ) walker . OnMatch ( " " , func ( file pkg . FileEntry ) error { br , berr := readBoshRelease ( file . Reader ) if berr != nil { return berr } r . BoshRelease [ br . ReleaseManifest . Name ] = br return nil } ) return walker . Walk ( ) }

// readPivnetRelease reads a pivnet release out of the given reader into a new
// pivnetRelease struct

readPivnetRelease reads a pivnet release out of the given reader into a new pivnetRelease struct


func decodeYaml(r io.Reader, v interface{}) error {
	bytes, err := ioutil.ReadAll(r)
	if err == nil {
		yaml.Unmarshal(bytes, v)
	}
	return err
}

func decodeYaml ( r io . Reader , v interface { } ) error { bytes , err := ioutil . ReadAll ( r ) if err == nil { yaml . Unmarshal ( bytes , v ) } return err }

// decodeYaml takes a reader to a YAML file and unmarshals it to the given struct.

decodeYaml takes a reader to a YAML file and unmarshals it to the given struct .


func NewZipWalker(zipFile string) Walker {
	return zipWalker{
		zipPath:   zipFile,
		callbacks: make(map[*regexp.Regexp]WalkFunc),
	}
}

func NewZipWalker ( zipFile string ) Walker { return zipWalker { zipPath : zipFile , callbacks : make ( map [ * regexp . Regexp ] WalkFunc ) , } }

// NewZipWalker creates a new Walker instance that can read a .zip stream

NewZipWalker creates a new Walker instance that can read a . zip stream


func NewDiffCmd(releaseRepo pull.Release, release1, release2 string) *DiffCmd {
	return &DiffCmd{
		releaseRepo: releaseRepo,
		release1:    release1,
		release2:    release2,
	}
}

func NewDiffCmd ( releaseRepo pull . Release , release1 , release2 string ) * DiffCmd { return & DiffCmd { releaseRepo : releaseRepo , release1 : release1 , release2 : release2 , } }

// NewDiffCmd creates a new DiffCmd instance.

NewDiffCmd creates a new DiffCmd instance .


func (s *DiffCmd) All(w io.Writer) error {
	differ, err := diff.New(s.releaseRepo, s.release1, s.release2)
	if err != nil {
		return err
	}
	d, err := differ.Diff()
	if err != nil {
		return err
	}
	s.printDiffResult(w, d)
	return nil
}

func ( s * DiffCmd ) All ( w io . Writer ) error { differ , err := diff . New ( s . releaseRepo , s . release1 , s . release2 ) if err != nil { return err } d , err := differ . Diff ( ) if err != nil { return err } s . printDiffResult ( w , d ) return nil }

// All writes out all the differences between the specified releases


func (s *DiffCmd) Job(job string, w io.Writer) error {
	differ, err := diff.New(s.releaseRepo, s.release1, s.release2)
	if err != nil {
		return err
	}
	d, err := differ.DiffJob(job)
	if err != nil {
		return err
	}
	s.printDiffResult(w, d)
	return nil
}

func ( s * DiffCmd ) Job ( job string , w io . Writer ) error { differ , err := diff . New ( s . releaseRepo , s . release1 , s . release2 ) if err != nil { return err } d , err := differ . DiffJob ( job ) if err != nil { return err } s . printDiffResult ( w , d ) return nil }

// Job writes out the job differences between the specified releases


func New(releaseRepo pull.Release, r1Path, r2Path string) (differ Differ, err error) {
	if filepath.Ext(r1Path) != filepath.Ext(r2Path) {
		err = fmt.Errorf("The specified releases didn't have matching file extensions, " +
			"assuming different release types.")
		return
	}
	if filepath.Ext(r1Path) == ".pivotal" {
		var r1, r2 *release.PivnetRelease
		if r1, err = release.LoadPivnetRelease(releaseRepo, r1Path); err == nil {
			if r2, err = release.LoadPivnetRelease(releaseRepo, r2Path); err == nil {
				differ = pivnetReleaseDiffer{
					release1: r1,
					release2: r2,
				}
			}
		}
	} else {
		var r1, r2 *release.BoshRelease
		if r1, err = release.LoadBoshRelease(releaseRepo, r1Path); err == nil {
			if r2, err = release.LoadBoshRelease(releaseRepo, r2Path); err == nil {
				differ = boshReleaseDiffer{
					release1: r1,
					release2: r2,
				}
			}
		}
	}
	return
}

func New ( releaseRepo pull . Release , r1Path , r2Path string ) ( differ Differ , err error ) { if filepath . Ext ( r1Path ) != filepath . Ext ( r2Path ) { err = fmt . Errorf ( " " + " " ) return } if filepath . Ext ( r1Path ) == " " { var r1 , r2 * release . PivnetRelease if r1 , err = release . LoadPivnetRelease ( releaseRepo , r1Path ) ; err == nil { if r2 , err = release . LoadPivnetRelease ( releaseRepo , r2Path ) ; err == nil { differ = pivnetReleaseDiffer { release1 : r1 , release2 : r2 , } } } } else { var r1 , r2 * release . BoshRelease if r1 , err = release . LoadBoshRelease ( releaseRepo , r1Path ) ; err == nil { if r2 , err = release . LoadBoshRelease ( releaseRepo , r2Path ) ; err == nil { differ = boshReleaseDiffer { release1 : r1 , release2 : r2 , } } } } return }

// New creates a Differ instance for comparing two releases


func (v *Record) StructName(i int, packagename string, properties []string) (structname string) {
	if i > 0 {
		currentNode := v.Slice[i-1]
		structname = FormatName(currentNode)
		if i > 1 {
			parentNames := v.FindAllParentsOfSameNamedElement(currentNode, properties)
			if len(parentNames) > 1 {
				structname = FormatName(v.Slice[i-2] + "_" + currentNode)
			}
		}
	} else {
		structname = FormatName(packagename + "_job")
	}
	return
}

func ( v * Record ) StructName ( i int , packagename string , properties [ ] string ) ( structname string ) { if i > 0 { currentNode := v . Slice [ i - 1 ] structname = FormatName ( currentNode ) if i > 1 { parentNames := v . FindAllParentsOfSameNamedElement ( currentNode , properties ) if len ( parentNames ) > 1 { structname = FormatName ( v . Slice [ i - 2 ] + " " + currentNode ) } } } else { structname = FormatName ( packagename + " " ) } return }

//StructName - gets struct name for property


func (v *Record) TypeName(i int, properties []string) (typename string) {
	if i+1 < v.Length {
		currentNode := v.Slice[i]
		typename = "*" + FormatName(currentNode)
		if i >= 1 {
			parentNames := v.FindAllParentsOfSameNamedElement(currentNode, properties)
			if len(parentNames) > 1 {
				typename = "*" + FormatName(v.Slice[i-1]+"_"+currentNode)
			}
		}
	} else {
		typename = "interface{}"
	}
	return
}

func ( v * Record ) TypeName ( i int , properties [ ] string ) ( typename string ) { if i + 1 < v . Length { currentNode := v . Slice [ i ] typename = " " + FormatName ( currentNode ) if i >= 1 { parentNames := v . FindAllParentsOfSameNamedElement ( currentNode , properties ) if len ( parentNames ) > 1 { typename = " " + FormatName ( v . Slice [ i - 1 ] + " " + currentNode ) } } } else { typename = " " } return }

//TypeName - returns valid type name for a give record


func NewTgzWalker(pkgReader io.Reader) Walker {
	return tgzWalker{
		pkgReader: pkgReader,
		callbacks: make(map[*regexp.Regexp]WalkFunc),
	}
}

func NewTgzWalker ( pkgReader io . Reader ) Walker { return tgzWalker { pkgReader : pkgReader , callbacks : make ( map [ * regexp . Regexp ] WalkFunc ) , } }

// NewTgzWalker creates a new Walker instance that can read a .tgz stream

NewTgzWalker creates a new Walker instance that can read a . tgz stream


func NewBackoff(strategy BackoffStrategy, start time.Duration, limit time.Duration) *Backoff {
	backoff := Backoff{strategy: strategy, start: start, limit: limit}
	backoff.Reset()
	return &backoff
}

func NewBackoff ( strategy BackoffStrategy , start time . Duration , limit time . Duration ) * Backoff { backoff := Backoff { strategy : strategy , start : start , limit : limit } backoff . Reset ( ) return & backoff }

// NewBackoff creates a new Backoff using the specified BackoffStrategy, start duration and limit.

NewBackoff creates a new Backoff using the specified BackoffStrategy start duration and limit .


func (b *Backoff) Reset() {
	b.count = 0
	b.LastDuration = 0
	b.NextDuration = b.getNextDuration()
}

func ( b * Backoff ) Reset ( ) { b . count = 0 b . LastDuration = 0 b . NextDuration = b . getNextDuration ( ) }

// Reset sets the Backoff to its initial conditions ready to start over.

Reset sets the Backoff to its initial conditions ready to start over .


func NewExponential(start time.Duration, limit time.Duration) *Backoff {
	return NewBackoff(exponential{}, start, limit)
}

func NewExponential ( start time . Duration , limit time . Duration ) * Backoff { return NewBackoff ( exponential { } , start , limit ) }

// NewExponential creates a new backoff using the exponential backoff algorithm.

NewExponential creates a new backoff using the exponential backoff algorithm .


func NewExponentialFullJitter(start time.Duration, limit time.Duration) *Backoff {
	return NewBackoff(exponentialFullJitter{limit: limit}, start, limit)
}

func NewExponentialFullJitter ( start time . Duration , limit time . Duration ) * Backoff { return NewBackoff ( exponentialFullJitter { limit : limit } , start , limit ) }

// NewExponentialFullJitter creates a new backoff using the exponential with full jitter backoff algorithm.

NewExponentialFullJitter creates a new backoff using the exponential with full jitter backoff algorithm .


func NewLinear(start time.Duration, limit time.Duration) *Backoff {
	return NewBackoff(linear{}, start, limit)
}

func NewLinear ( start time . Duration , limit time . Duration ) * Backoff { return NewBackoff ( linear { } , start , limit ) }

// NewLinear creates a new backoff using the linear backoff algorithm.

NewLinear creates a new backoff using the linear backoff algorithm .


func (s *Sapin) GetLineSize(floor, line int) int {
	return 1 + line*2 + floor*4 + int(floor/2*2)*int((floor+1)/2)
}

func ( s * Sapin ) GetLineSize ( floor , line int ) int { return 1 + line * 2 + floor * 4 + int ( floor / 2 * 2 ) * int ( ( floor + 1 ) / 2 ) }

// GetLineSize returns the size of the sapin for a specified floor and line.

GetLineSize returns the size of the sapin for a specified floor and line .


func (s *Sapin) GetMaxSize() int {
	return s.GetLineSize(s.Size-1, s.Size+3)
}

func ( s * Sapin ) GetMaxSize ( ) int { return s . GetLineSize ( s . Size - 1 , s . Size + 3 ) }

// GetMaxSize returns the size of the widest part of the sapin.

GetMaxSize returns the size of the widest part of the sapin .


func (s *Sapin) compute() {
	if s.output != "" {
		return
	}
	// size of the last line of the last floor
	maxSize := s.GetMaxSize()

	// each floor in the floors
	for floor := 0; floor < s.Size; floor++ {

		// each line in the lines of the floor
		for line := 0; line < floor+4; line++ {

			// size of the current line
			lineSize := s.GetLineSize(floor, line)

			// pad left with spaces
			for i := (maxSize-lineSize)/2 - 1; i > 0; i-- {
				s.putchar(" ")
			}

			// draw the body
			for i := 0; i < lineSize; i++ {
				s.putchar("*")
			}

			// new line
			s.putchar("\n")
		}
	}

	// the trunc
	for i := 0; i < s.Size; i++ {
		lineSize := s.Size + (s.Size+1)%2

		// pad left with spaces
		for i := (maxSize-lineSize)/2 - 1; i > 0; i-- {
			s.putchar(" ")
		}

		// draw the body
		for i := 0; i < lineSize; i++ {
			s.putchar("|")
		}

		// new line
		s.putchar("\n")
	}
}

// compute iterates over floors and lines to generate the output of the sapin.

compute iterates over floors and lines to generate the output of the sapin .


func (o *PostAppsParams) WithTimeout(timeout time.Duration) *PostAppsParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * PostAppsParams ) WithTimeout ( timeout time . Duration ) * PostAppsParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the post apps params


func (o *PostAppsParams) WithContext(ctx context.Context) *PostAppsParams {
	o.SetContext(ctx)
	return o
}

func ( o * PostAppsParams ) WithContext ( ctx context . Context ) * PostAppsParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the post apps params


func (o *PostAppsParams) WithHTTPClient(client *http.Client) *PostAppsParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * PostAppsParams ) WithHTTPClient ( client * http . Client ) * PostAppsParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the post apps params


func (o *PostAppsParams) WithBody(body *models.AppWrapper) *PostAppsParams {
	o.SetBody(body)
	return o
}

func ( o * PostAppsParams ) WithBody ( body * models . AppWrapper ) * PostAppsParams { o . SetBody ( body ) return o }

// WithBody adds the body to the post apps params


func (o *GetAppsAppParams) WithTimeout(timeout time.Duration) *GetAppsAppParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * GetAppsAppParams ) WithTimeout ( timeout time . Duration ) * GetAppsAppParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the get apps app params


func (o *GetAppsAppParams) WithContext(ctx context.Context) *GetAppsAppParams {
	o.SetContext(ctx)
	return o
}

func ( o * GetAppsAppParams ) WithContext ( ctx context . Context ) * GetAppsAppParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the get apps app params


func (o *GetAppsAppParams) WithHTTPClient(client *http.Client) *GetAppsAppParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * GetAppsAppParams ) WithHTTPClient ( client * http . Client ) * GetAppsAppParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the get apps app params


func (o *GetAppsAppParams) WithApp(app string) *GetAppsAppParams {
	o.SetApp(app)
	return o
}

func ( o * GetAppsAppParams ) WithApp ( app string ) * GetAppsAppParams { o . SetApp ( app ) return o }

// WithApp adds the app to the get apps app params


func (m *RouteWrapper) UnmarshalBinary(b []byte) error {
	var res RouteWrapper
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

func ( m * RouteWrapper ) UnmarshalBinary ( b [ ] byte ) error { var res RouteWrapper if err := swag . ReadJSON ( b , & res ) ; err != nil { return err } * m = res return nil }

// UnmarshalBinary interface implementation


func (o *GetAppsParams) WithTimeout(timeout time.Duration) *GetAppsParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * GetAppsParams ) WithTimeout ( timeout time . Duration ) * GetAppsParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the get apps params


func (o *GetAppsParams) WithContext(ctx context.Context) *GetAppsParams {
	o.SetContext(ctx)
	return o
}

func ( o * GetAppsParams ) WithContext ( ctx context . Context ) * GetAppsParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the get apps params


func (o *GetAppsParams) WithHTTPClient(client *http.Client) *GetAppsParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * GetAppsParams ) WithHTTPClient ( client * http . Client ) * GetAppsParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the get apps params


func (o *DeleteAppsAppParams) WithTimeout(timeout time.Duration) *DeleteAppsAppParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * DeleteAppsAppParams ) WithTimeout ( timeout time . Duration ) * DeleteAppsAppParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the delete apps app params


func (o *DeleteAppsAppParams) WithContext(ctx context.Context) *DeleteAppsAppParams {
	o.SetContext(ctx)
	return o
}

func ( o * DeleteAppsAppParams ) WithContext ( ctx context . Context ) * DeleteAppsAppParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the delete apps app params


func (o *DeleteAppsAppParams) WithHTTPClient(client *http.Client) *DeleteAppsAppParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * DeleteAppsAppParams ) WithHTTPClient ( client * http . Client ) * DeleteAppsAppParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the delete apps app params


func (o *DeleteAppsAppParams) WithApp(app string) *DeleteAppsAppParams {
	o.SetApp(app)
	return o
}

func ( o * DeleteAppsAppParams ) WithApp ( app string ) * DeleteAppsAppParams { o . SetApp ( app ) return o }

// WithApp adds the app to the delete apps app params


func (o *PatchAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *PatchAppsAppRoutesRouteParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * PatchAppsAppRoutesRouteParams ) WithTimeout ( timeout time . Duration ) * PatchAppsAppRoutesRouteParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the patch apps app routes route params


func (o *PatchAppsAppRoutesRouteParams) WithContext(ctx context.Context) *PatchAppsAppRoutesRouteParams {
	o.SetContext(ctx)
	return o
}

func ( o * PatchAppsAppRoutesRouteParams ) WithContext ( ctx context . Context ) * PatchAppsAppRoutesRouteParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the patch apps app routes route params


func (o *PatchAppsAppRoutesRouteParams) WithHTTPClient(client *http.Client) *PatchAppsAppRoutesRouteParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * PatchAppsAppRoutesRouteParams ) WithHTTPClient ( client * http . Client ) * PatchAppsAppRoutesRouteParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the patch apps app routes route params


func (o *PatchAppsAppRoutesRouteParams) WithApp(app string) *PatchAppsAppRoutesRouteParams {
	o.SetApp(app)
	return o
}

func ( o * PatchAppsAppRoutesRouteParams ) WithApp ( app string ) * PatchAppsAppRoutesRouteParams { o . SetApp ( app ) return o }

// WithApp adds the app to the patch apps app routes route params


func (o *PatchAppsAppRoutesRouteParams) WithBody(body *models.RouteWrapper) *PatchAppsAppRoutesRouteParams {
	o.SetBody(body)
	return o
}

func ( o * PatchAppsAppRoutesRouteParams ) WithBody ( body * models . RouteWrapper ) * PatchAppsAppRoutesRouteParams { o . SetBody ( body ) return o }

// WithBody adds the body to the patch apps app routes route params


func (o *PatchAppsAppRoutesRouteParams) WithRoute(route string) *PatchAppsAppRoutesRouteParams {
	o.SetRoute(route)
	return o
}

func ( o * PatchAppsAppRoutesRouteParams ) WithRoute ( route string ) * PatchAppsAppRoutesRouteParams { o . SetRoute ( route ) return o }

// WithRoute adds the route to the patch apps app routes route params


func (o *PostAppsAppRoutesParams) WithTimeout(timeout time.Duration) *PostAppsAppRoutesParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * PostAppsAppRoutesParams ) WithTimeout ( timeout time . Duration ) * PostAppsAppRoutesParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the post apps app routes params


func (o *PostAppsAppRoutesParams) WithContext(ctx context.Context) *PostAppsAppRoutesParams {
	o.SetContext(ctx)
	return o
}

func ( o * PostAppsAppRoutesParams ) WithContext ( ctx context . Context ) * PostAppsAppRoutesParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the post apps app routes params


func (o *PostAppsAppRoutesParams) WithHTTPClient(client *http.Client) *PostAppsAppRoutesParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * PostAppsAppRoutesParams ) WithHTTPClient ( client * http . Client ) * PostAppsAppRoutesParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the post apps app routes params


func (o *PostAppsAppRoutesParams) WithApp(app string) *PostAppsAppRoutesParams {
	o.SetApp(app)
	return o
}

func ( o * PostAppsAppRoutesParams ) WithApp ( app string ) * PostAppsAppRoutesParams { o . SetApp ( app ) return o }

// WithApp adds the app to the post apps app routes params


func (o *PostAppsAppRoutesParams) WithBody(body *models.RouteWrapper) *PostAppsAppRoutesParams {
	o.SetBody(body)
	return o
}

func ( o * PostAppsAppRoutesParams ) WithBody ( body * models . RouteWrapper ) * PostAppsAppRoutesParams { o . SetBody ( body ) return o }

// WithBody adds the body to the post apps app routes params


func (o *PutAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *PutAppsAppRoutesRouteParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * PutAppsAppRoutesRouteParams ) WithTimeout ( timeout time . Duration ) * PutAppsAppRoutesRouteParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the put apps app routes route params


func (o *PutAppsAppRoutesRouteParams) WithContext(ctx context.Context) *PutAppsAppRoutesRouteParams {
	o.SetContext(ctx)
	return o
}

func ( o * PutAppsAppRoutesRouteParams ) WithContext ( ctx context . Context ) * PutAppsAppRoutesRouteParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the put apps app routes route params


func (o *PutAppsAppRoutesRouteParams) WithApp(app string) *PutAppsAppRoutesRouteParams {
	o.SetApp(app)
	return o
}

func ( o * PutAppsAppRoutesRouteParams ) WithApp ( app string ) * PutAppsAppRoutesRouteParams { o . SetApp ( app ) return o }

// WithApp adds the app to the put apps app routes route params


func (o *PutAppsAppRoutesRouteParams) WithBody(body *models.RouteWrapper) *PutAppsAppRoutesRouteParams {
	o.SetBody(body)
	return o
}

func ( o * PutAppsAppRoutesRouteParams ) WithBody ( body * models . RouteWrapper ) * PutAppsAppRoutesRouteParams { o . SetBody ( body ) return o }

// WithBody adds the body to the put apps app routes route params


func (o *PutAppsAppRoutesRouteParams) WithRoute(route string) *PutAppsAppRoutesRouteParams {
	o.SetRoute(route)
	return o
}

func ( o * PutAppsAppRoutesRouteParams ) WithRoute ( route string ) * PutAppsAppRoutesRouteParams { o . SetRoute ( route ) return o }

// WithRoute adds the route to the put apps app routes route params


func (o *GetAppsAppRoutesParams) WithTimeout(timeout time.Duration) *GetAppsAppRoutesParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * GetAppsAppRoutesParams ) WithTimeout ( timeout time . Duration ) * GetAppsAppRoutesParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the get apps app routes params


func (o *GetAppsAppRoutesParams) WithContext(ctx context.Context) *GetAppsAppRoutesParams {
	o.SetContext(ctx)
	return o
}

func ( o * GetAppsAppRoutesParams ) WithContext ( ctx context . Context ) * GetAppsAppRoutesParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the get apps app routes params


func (o *GetAppsAppRoutesParams) WithHTTPClient(client *http.Client) *GetAppsAppRoutesParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * GetAppsAppRoutesParams ) WithHTTPClient ( client * http . Client ) * GetAppsAppRoutesParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the get apps app routes params


func (o *GetAppsAppRoutesParams) WithApp(app string) *GetAppsAppRoutesParams {
	o.SetApp(app)
	return o
}

func ( o * GetAppsAppRoutesParams ) WithApp ( app string ) * GetAppsAppRoutesParams { o . SetApp ( app ) return o }

// WithApp adds the app to the get apps app routes params


func (o *PatchAppsAppParams) WithTimeout(timeout time.Duration) *PatchAppsAppParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * PatchAppsAppParams ) WithTimeout ( timeout time . Duration ) * PatchAppsAppParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the patch apps app params


func (o *PatchAppsAppParams) WithContext(ctx context.Context) *PatchAppsAppParams {
	o.SetContext(ctx)
	return o
}

func ( o * PatchAppsAppParams ) WithContext ( ctx context . Context ) * PatchAppsAppParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the patch apps app params


func (o *PatchAppsAppParams) WithHTTPClient(client *http.Client) *PatchAppsAppParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * PatchAppsAppParams ) WithHTTPClient ( client * http . Client ) * PatchAppsAppParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the patch apps app params


func (o *PatchAppsAppParams) WithApp(app string) *PatchAppsAppParams {
	o.SetApp(app)
	return o
}

func ( o * PatchAppsAppParams ) WithApp ( app string ) * PatchAppsAppParams { o . SetApp ( app ) return o }

// WithApp adds the app to the patch apps app params


func (o *PatchAppsAppParams) WithBody(body *models.AppWrapper) *PatchAppsAppParams {
	o.SetBody(body)
	return o
}

func ( o * PatchAppsAppParams ) WithBody ( body * models . AppWrapper ) * PatchAppsAppParams { o . SetBody ( body ) return o }

// WithBody adds the body to the patch apps app params


func (o *PutAppsAppParams) WithTimeout(timeout time.Duration) *PutAppsAppParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * PutAppsAppParams ) WithTimeout ( timeout time . Duration ) * PutAppsAppParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the put apps app params


func (o *PutAppsAppParams) WithContext(ctx context.Context) *PutAppsAppParams {
	o.SetContext(ctx)
	return o
}

func ( o * PutAppsAppParams ) WithContext ( ctx context . Context ) * PutAppsAppParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the put apps app params


func (o *PutAppsAppParams) WithApp(app string) *PutAppsAppParams {
	o.SetApp(app)
	return o
}

func ( o * PutAppsAppParams ) WithApp ( app string ) * PutAppsAppParams { o . SetApp ( app ) return o }

// WithApp adds the app to the put apps app params


func (o *PutAppsAppParams) WithBody(body *models.AppWrapper) *PutAppsAppParams {
	o.SetBody(body)
	return o
}

func ( o * PutAppsAppParams ) WithBody ( body * models . AppWrapper ) * PutAppsAppParams { o . SetBody ( body ) return o }

// WithBody adds the body to the put apps app params


func (m *Task) UnmarshalJSON(raw []byte) error {

	var aO0 NewTask
	if err := swag.ReadJSON(raw, &aO0); err != nil {
		return err
	}
	m.NewTask = aO0

	var aO1 TaskAllOf1
	if err := swag.ReadJSON(raw, &aO1); err != nil {
		return err
	}
	m.TaskAllOf1 = aO1

	return nil
}

func ( m * Task ) UnmarshalJSON ( raw [ ] byte ) error { var aO0 NewTask if err := swag . ReadJSON ( raw , & aO0 ) ; err != nil { return err } m . NewTask = aO0 var aO1 TaskAllOf1 if err := swag . ReadJSON ( raw , & aO1 ) ; err != nil { return err } m . TaskAllOf1 = aO1 return nil }

// UnmarshalJSON unmarshals this object from a JSON structure


func (m Task) MarshalJSON() ([]byte, error) {
	var _parts [][]byte

	aO0, err := swag.WriteJSON(m.NewTask)
	if err != nil {
		return nil, err
	}
	_parts = append(_parts, aO0)

	aO1, err := swag.WriteJSON(m.TaskAllOf1)
	if err != nil {
		return nil, err
	}
	_parts = append(_parts, aO1)

	return swag.ConcatJSON(_parts...), nil
}

func ( m Task ) MarshalJSON ( ) ( [ ] byte , error ) { var _parts [ ] [ ] byte aO0 , err := swag . WriteJSON ( m . NewTask ) if err != nil { return nil , err } _parts = append ( _parts , aO0 ) aO1 , err := swag . WriteJSON ( m . TaskAllOf1 ) if err != nil { return nil , err } _parts = append ( _parts , aO1 ) return swag . ConcatJSON ( _parts ... ) , nil }

// MarshalJSON marshals this object to a JSON structure


func (m *Task) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.NewTask.Validate(formats); err != nil {
		res = append(res, err)
	}

	if err := m.TaskAllOf1.Validate(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func ( m * Task ) Validate ( formats strfmt . Registry ) error { var res [ ] error if err := m . NewTask . Validate ( formats ) ; err != nil { res = append ( res , err ) } if err := m . TaskAllOf1 . Validate ( formats ) ; err != nil { res = append ( res , err ) } if len ( res ) > 0 { return errors . CompositeValidationError ( res ... ) } return nil }


func GetRanges(ips []string, ip4_cidr string, ip6_cidr string) ([]net.IPNet, error) {
	net_out := make([]net.IPNet, 0)

	for _, ip := range ips {
		cidr := ""
		if strings.Contains(ip, ":") {
			// IPv6
			cidr = ip6_cidr
			if cidr == "" {
				cidr = "128"
			}
			if c, err := strconv.ParseInt(cidr, 10, 16); err != nil || c < 0 || c > 128 {
				return nil, &PermError{"Invalid IPv6 CIDR length: " + cidr}
			}

		} else {
			// IPv4
			cidr = ip4_cidr
			if cidr == "" {
				cidr = "32"
			}
			if c, err := strconv.ParseInt(cidr, 10, 16); err != nil || c < 0 || c > 32 {
				return nil, &PermError{"Invalid IPv4 CIDR length: " + cidr}
			}
		}
		ip += "/" + cidr

		_, ipnet, err := net.ParseCIDR(ip)
		if err != nil {
			return nil, err
		}
		net_out = append(net_out, *ipnet)

	}

	return net_out, nil
}

func
GetRanges
(
ips
[
]
string
,
ip4_cidr
string
,
ip6_cidr
string
)
(
[
]
net
.
IPNet
,
error
)
{
net_out
:=
make
(
[
]
net
.
IPNet
,
0
)
for
_
,
ip
:=
range
ips
{
cidr
:=
"
"
if
strings
.
Contains
(
ip
,
"
"
)
{
// IPv6
cidr
=
ip6_cidr
if
cidr
==
"
"
{
cidr
=
"
"
}
if
c
,
err
:=
strconv
.
ParseInt
(
cidr
,
10
,
16
)
;
err
!=
||
c
<
0
||
c
>
128
{
return
,
&
PermError
{
"
"
+
cidr
}
}
}
else
{
// IPv4
cidr
=
ip4_cidr
if
cidr
==
"
"
{
cidr
=
"
"
}
if
c
,
err
:=
strconv
.
ParseInt
(
cidr
,
10
,
16
)
;
err
!=
||
c
<
0
||
c
>
32
{
return
,
&
PermError
{
"
"
+
cidr
}
}
}
ip
+=
"
"
+
cidr
_
,
ipnet
,
err
:=
net
.
ParseCIDR
(
ip
)
if
err
!=
{
return
,
err
}
net_out
=
append
(
net_out
,
*
ipnet
)
}
return
net_out
,
}

// GetRanges composes the CIDR IP ranges following RFC 4632 and RFC 4291
// of the given IPs, with a given IPv4 CIDR and IPv6 CIDR

GetRanges composes the CIDR IP ranges following RFC 4632 and RFC 4291 of the given IPs with a given IPv4 CIDR and IPv6 CIDR


func (o *GetAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *GetAppsAppRoutesRouteParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * GetAppsAppRoutesRouteParams ) WithTimeout ( timeout time . Duration ) * GetAppsAppRoutesRouteParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the get apps app routes route params


func (o *GetAppsAppRoutesRouteParams) WithContext(ctx context.Context) *GetAppsAppRoutesRouteParams {
	o.SetContext(ctx)
	return o
}

func ( o * GetAppsAppRoutesRouteParams ) WithContext ( ctx context . Context ) * GetAppsAppRoutesRouteParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the get apps app routes route params


func (o *GetAppsAppRoutesRouteParams) WithHTTPClient(client *http.Client) *GetAppsAppRoutesRouteParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * GetAppsAppRoutesRouteParams ) WithHTTPClient ( client * http . Client ) * GetAppsAppRoutesRouteParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the get apps app routes route params


func (o *GetAppsAppRoutesRouteParams) WithApp(app string) *GetAppsAppRoutesRouteParams {
	o.SetApp(app)
	return o
}

func ( o * GetAppsAppRoutesRouteParams ) WithApp ( app string ) * GetAppsAppRoutesRouteParams { o . SetApp ( app ) return o }

// WithApp adds the app to the get apps app routes route params


func (o *GetAppsAppRoutesRouteParams) WithRoute(route string) *GetAppsAppRoutesRouteParams {
	o.SetRoute(route)
	return o
}

func ( o * GetAppsAppRoutesRouteParams ) WithRoute ( route string ) * GetAppsAppRoutesRouteParams { o . SetRoute ( route ) return o }

// WithRoute adds the route to the get apps app routes route params


func New(transport runtime.ClientTransport, formats strfmt.Registry) *Functions {
	cli := new(Functions)
	cli.Transport = transport

	cli.Apps = apps.New(transport, formats)

	cli.Routes = routes.New(transport, formats)

	cli.Tasks = tasks.New(transport, formats)

	cli.Version = version.New(transport, formats)

	return cli
}

func New ( transport runtime . ClientTransport , formats strfmt . Registry ) * Functions { cli := new ( Functions ) cli . Transport = transport cli . Apps = apps . New ( transport , formats ) cli . Routes = routes . New ( transport , formats ) cli . Tasks = tasks . New ( transport , formats ) cli . Version = version . New ( transport , formats ) return cli }


func (c *Functions) SetTransport(transport runtime.ClientTransport) {
	c.Transport = transport

	c.Apps.SetTransport(transport)

	c.Routes.SetTransport(transport)

	c.Tasks.SetTransport(transport)

	c.Version.SetTransport(transport)

}

func ( c * Functions ) SetTransport ( transport runtime . ClientTransport ) { c . Transport = transport c . Apps . SetTransport ( transport ) c . Routes . SetTransport ( transport ) c . Tasks . SetTransport ( transport ) c . Version . SetTransport ( transport ) }

// SetTransport changes the transport on the client and all its subresources


func (o *DeleteAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *DeleteAppsAppRoutesRouteParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * DeleteAppsAppRoutesRouteParams ) WithTimeout ( timeout time . Duration ) * DeleteAppsAppRoutesRouteParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the delete apps app routes route params


func (o *DeleteAppsAppRoutesRouteParams) WithContext(ctx context.Context) *DeleteAppsAppRoutesRouteParams {
	o.SetContext(ctx)
	return o
}

func ( o * DeleteAppsAppRoutesRouteParams ) WithContext ( ctx context . Context ) * DeleteAppsAppRoutesRouteParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the delete apps app routes route params


func (o *DeleteAppsAppRoutesRouteParams) WithHTTPClient(client *http.Client) *DeleteAppsAppRoutesRouteParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * DeleteAppsAppRoutesRouteParams ) WithHTTPClient ( client * http . Client ) * DeleteAppsAppRoutesRouteParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the delete apps app routes route params


func (o *DeleteAppsAppRoutesRouteParams) WithApp(app string) *DeleteAppsAppRoutesRouteParams {
	o.SetApp(app)
	return o
}

func ( o * DeleteAppsAppRoutesRouteParams ) WithApp ( app string ) * DeleteAppsAppRoutesRouteParams { o . SetApp ( app ) return o }

// WithApp adds the app to the delete apps app routes route params


func (o *DeleteAppsAppRoutesRouteParams) WithRoute(route string) *DeleteAppsAppRoutesRouteParams {
	o.SetRoute(route)
	return o
}

func ( o * DeleteAppsAppRoutesRouteParams ) WithRoute ( route string ) * DeleteAppsAppRoutesRouteParams { o . SetRoute ( route ) return o }

// WithRoute adds the route to the delete apps app routes route params


func (o *GetTasksParams) WithTimeout(timeout time.Duration) *GetTasksParams {
	o.SetTimeout(timeout)
	return o
}

func ( o * GetTasksParams ) WithTimeout ( timeout time . Duration ) * GetTasksParams { o . SetTimeout ( timeout ) return o }

// WithTimeout adds the timeout to the get tasks params


func (o *GetTasksParams) WithContext(ctx context.Context) *GetTasksParams {
	o.SetContext(ctx)
	return o
}

func ( o * GetTasksParams ) WithContext ( ctx context . Context ) * GetTasksParams { o . SetContext ( ctx ) return o }

// WithContext adds the context to the get tasks params


func (o *GetTasksParams) WithHTTPClient(client *http.Client) *GetTasksParams {
	o.SetHTTPClient(client)
	return o
}

func ( o * GetTasksParams ) WithHTTPClient ( client * http . Client ) * GetTasksParams { o . SetHTTPClient ( client ) return o }

// WithHTTPClient adds the HTTPClient to the get tasks params


func NewValueStore(addr string, concurrency int, ftlsConfig *ftls.Config, opts ...grpc.DialOption) (store.ValueStore, error) {
	stor := &valueStore{
		addr:             addr,
		ftlsc:            ftlsConfig,
		opts:             opts,
		handlersDoneChan: make(chan struct{}),
	}

	stor.pendingLookupReqChan = make(chan *asyncValueLookupRequest, concurrency)
	stor.freeLookupReqChan = make(chan *asyncValueLookupRequest, concurrency)
	stor.freeLookupResChan = make(chan *asyncValueLookupResponse, concurrency)
	for i := 0; i < cap(stor.freeLookupReqChan); i++ {
		stor.freeLookupReqChan <- &asyncValueLookupRequest{resChan: make(chan *asyncValueLookupResponse, 1)}
	}
	for i := 0; i < cap(stor.freeLookupResChan); i++ {
		stor.freeLookupResChan <- &asyncValueLookupResponse{}
	}
	go stor.handleLookupStream()

	stor.pendingReadReqChan = make(chan *asyncValueReadRequest, concurrency)
	stor.freeReadReqChan = make(chan *asyncValueReadRequest, concurrency)
	stor.freeReadResChan = make(chan *asyncValueReadResponse, concurrency)
	for i := 0; i < cap(stor.freeReadReqChan); i++ {
		stor.freeReadReqChan <- &asyncValueReadRequest{resChan: make(chan *asyncValueReadResponse, 1)}
	}
	for i := 0; i < cap(stor.freeReadResChan); i++ {
		stor.freeReadResChan <- &asyncValueReadResponse{}
	}
	go stor.handleReadStream()

	stor.pendingWriteReqChan = make(chan *asyncValueWriteRequest, concurrency)
	stor.freeWriteReqChan = make(chan *asyncValueWriteRequest, concurrency)
	stor.freeWriteResChan = make(chan *asyncValueWriteResponse, concurrency)
	for i := 0; i < cap(stor.freeWriteReqChan); i++ {
		stor.freeWriteReqChan <- &asyncValueWriteRequest{resChan: make(chan *asyncValueWriteResponse, 1)}
	}
	for i := 0; i < cap(stor.freeWriteResChan); i++ {
		stor.freeWriteResChan <- &asyncValueWriteResponse{}
	}
	go stor.handleWriteStream()

	stor.pendingDeleteReqChan = make(chan *asyncValueDeleteRequest, concurrency)
	stor.freeDeleteReqChan = make(chan *asyncValueDeleteRequest, concurrency)
	stor.freeDeleteResChan = make(chan *asyncValueDeleteResponse, concurrency)
	for i := 0; i < cap(stor.freeDeleteReqChan); i++ {
		stor.freeDeleteReqChan <- &asyncValueDeleteRequest{resChan: make(chan *asyncValueDeleteResponse, 1)}
	}
	for i := 0; i < cap(stor.freeDeleteResChan); i++ {
		stor.freeDeleteResChan <- &asyncValueDeleteResponse{}
	}
	go stor.handleDeleteStream()

	return stor, nil
}

func NewValueStore ( addr string , concurrency int , ftlsConfig * ftls . Config , opts ... grpc . DialOption ) ( store . ValueStore , error ) { stor := & valueStore { addr : addr , ftlsc : ftlsConfig , opts : opts , handlersDoneChan : make ( chan struct { } ) , } stor . pendingLookupReqChan = make ( chan * asyncValueLookupRequest , concurrency ) stor . freeLookupReqChan = make ( chan * asyncValueLookupRequest , concurrency ) stor . freeLookupResChan = make ( chan * asyncValueLookupResponse , concurrency ) for i := 0 ; i < cap ( stor . freeLookupReqChan ) ; i ++ { stor . freeLookupReqChan <- & asyncValueLookupRequest { resChan : make ( chan * asyncValueLookupResponse , 1 ) } } for i := 0 ; i < cap ( stor . freeLookupResChan ) ; i ++ { stor . freeLookupResChan <- & asyncValueLookupResponse { } } go stor . handleLookupStream ( ) stor . pendingReadReqChan = make ( chan * asyncValueReadRequest , concurrency ) stor . freeReadReqChan = make ( chan * asyncValueReadRequest , concurrency ) stor . freeReadResChan = make ( chan * asyncValueReadResponse , concurrency ) for i := 0 ; i < cap ( stor . freeReadReqChan ) ; i ++ { stor . freeReadReqChan <- & asyncValueReadRequest { resChan : make ( chan * asyncValueReadResponse , 1 ) } } for i := 0 ; i < cap ( stor . freeReadResChan ) ; i ++ { stor . freeReadResChan <- & asyncValueReadResponse { } } go stor . handleReadStream ( ) stor . pendingWriteReqChan = make ( chan * asyncValueWriteRequest , concurrency ) stor . freeWriteReqChan = make ( chan * asyncValueWriteRequest , concurrency ) stor . freeWriteResChan = make ( chan * asyncValueWriteResponse , concurrency ) for i := 0 ; i < cap ( stor . freeWriteReqChan ) ; i ++ { stor . freeWriteReqChan <- & asyncValueWriteRequest { resChan : make ( chan * asyncValueWriteResponse , 1 ) } } for i := 0 ; i < cap ( stor . freeWriteResChan ) ; i ++ { stor . freeWriteResChan <- & asyncValueWriteResponse { } } go stor . handleWriteStream ( ) stor . pendingDeleteReqChan = make ( chan * asyncValueDeleteRequest , concurrency ) stor . freeDeleteReqChan = make ( chan * asyncValueDeleteRequest , concurrency ) stor . freeDeleteResChan = make ( chan * asyncValueDeleteResponse , concurrency ) for i := 0 ; i < cap ( stor . freeDeleteReqChan ) ; i ++ { stor . freeDeleteReqChan <- & asyncValueDeleteRequest { resChan : make ( chan * asyncValueDeleteResponse , 1 ) } } for i := 0 ; i < cap ( stor . freeDeleteResChan ) ; i ++ { stor . freeDeleteResChan <- & asyncValueDeleteResponse { } } go stor . handleDeleteStream ( ) return stor , nil }

// NewValueStore creates a ValueStore connection via grpc to the given
// address.

NewValueStore creates a ValueStore connection via grpc to the given address .


func (stor *valueStore) Close() {
	stor.lock.Lock()
	stor.shutdown()
	close(stor.handlersDoneChan)
	stor.lock.Unlock()
}

func ( stor * valueStore ) Close ( ) { stor . lock . Lock ( ) stor . shutdown ( ) close ( stor . handlersDoneChan ) stor . lock . Unlock ( ) }

// Close will shutdown outgoing connectivity and stop all background
// goroutines; note that the valueStore is no longer usable after a call to
// Close, including using Startup.

Close will shutdown outgoing connectivity and stop all background goroutines ; note that the valueStore is no longer usable after a call to Close including using Startup .


func (o *Server) SetBackend(backend OortService) {
	o.Lock()
	o.backend = backend
	o.Unlock()
}

func ( o * Server ) SetBackend ( backend OortService ) { o . Lock ( ) o . backend = backend o . Unlock ( ) }


func (o *Server) Ring() ring.Ring {
	o.RLock()
	defer o.RUnlock()
	return o.ring
}

func ( o * Server ) Ring ( ) ring . Ring { o . RLock ( ) defer o . RUnlock ( ) return o . ring }

// Ring returns an instance of the current Ring


func (o *Server) GetLocalID() uint64 {
	o.RLock()
	defer o.RUnlock()
	return o.localID
}

func ( o * Server ) GetLocalID ( ) uint64 { o . RLock ( ) defer o . RUnlock ( ) return o . localID }

// GetLocalID returns the current local id


func (o *Server) GetListenAddr() string {
	o.RLock()
	defer o.RUnlock()
	return o.ring.LocalNode().Address(2)
}

func ( o * Server ) GetListenAddr ( ) string { o . RLock ( ) defer o . RUnlock ( ) return o . ring . LocalNode ( ) . Address ( 2 ) }

// GetListenAddr returns the current localnode.address2 instance

GetListenAddr returns the current localnode . address2 instance


func (rs *ReplGroupStore) Startup(ctx context.Context) error {
	rs.ringLock.Lock()
	if rs.ringServerExitChan == nil {
		rs.ringServerExitChan = make(chan struct{})
		go rs.ringServerConnector(rs.ringServerExitChan)
	}
	rs.ringLock.Unlock()
	return nil
}

func ( rs * ReplGroupStore ) Startup ( ctx context . Context ) error { rs . ringLock . Lock ( ) if rs . ringServerExitChan == nil { rs . ringServerExitChan = make ( chan struct { } ) go rs . ringServerConnector ( rs . ringServerExitChan ) } rs . ringLock . Unlock ( ) return nil }

// Startup is not required to use the ReplGroupStore; it will automatically
// connect to backend stores as needed. However, if you'd like to use the ring
// service to receive ring updates and have the ReplGroupStore automatically
// update itself accordingly, Startup will launch a connector to that service.
// Otherwise, you will need to call SetRing yourself to inform the
// ReplGroupStore of which backends to connect to.

Startup is not required to use the ReplGroupStore ; it will automatically connect to backend stores as needed . However if you d like to use the ring service to receive ring updates and have the ReplGroupStore automatically update itself accordingly Startup will launch a connector to that service . Otherwise you will need to call SetRing yourself to inform the ReplGroupStore of which backends to connect to .


func (o *Server) shutdownFinished() {
	time.Sleep(10 * time.Millisecond)
	close(o.ShutdownComplete)
}

func ( o * Server ) shutdownFinished ( ) { time . Sleep ( 10 * time . Millisecond ) close ( o . ShutdownComplete ) }

// shutdownFinished closes the shutdownComplete channel
// 10 miliseconds after being invoked (to give a cmd ctrl client
// a chance to return.

shutdownFinished closes the shutdownComplete channel 10 miliseconds after being invoked ( to give a cmd ctrl client a chance to return .


func (o *Server) Stop() error {
	o.cmdCtrlLock.Lock()
	defer o.cmdCtrlLock.Unlock()
	if o.stopped {
		return fmt.Errorf("Service already stopped")
	}
	close(o.ch)
	o.backend.StopListenAndServe()
	o.backend.Wait()
	o.backend.Stop()
	o.stopped = true
	return nil
}

func ( o * Server ) Stop ( ) error { o . cmdCtrlLock . Lock ( ) defer o . cmdCtrlLock . Unlock ( ) if o . stopped { return fmt . Errorf ( " " ) } close ( o . ch ) o . backend . StopListenAndServe ( ) o . backend . Wait ( ) o . backend . Stop ( ) o . stopped = true return nil }

// Stop the backend and shutdown all listeners.
// Does NOT exist the process.

Stop the backend and shutdown all listeners . Does NOT exist the process .


func (o *Server) Exit() error {
	o.cmdCtrlLock.Lock()
	defer o.cmdCtrlLock.Unlock()
	if o.stopped {
		o.backend.Stop()
		defer o.shutdownFinished()
		return nil
	}
	close(o.ch)
	o.backend.StopListenAndServe()
	o.backend.Wait()
	o.backend.Stop()
	o.stopped = true
	defer o.shutdownFinished()
	return nil
}

func ( o * Server ) Exit ( ) error { o . cmdCtrlLock . Lock ( ) defer o . cmdCtrlLock . Unlock ( ) if o . stopped { o . backend . Stop ( ) defer o . shutdownFinished ( ) return nil } close ( o . ch ) o . backend . StopListenAndServe ( ) o . backend . Wait ( ) o . backend . Stop ( ) o . stopped = true defer o . shutdownFinished ( ) return nil }

// Exit the backend and shutdown all listeners.
// Closes the ShutdownComplete chan when finsihed.

Exit the backend and shutdown all listeners . Closes the ShutdownComplete chan when finsihed .


func (o *Server) SelfUpgrade(version string, bindiff, checksum []byte) (bool, string) {
	o.cmdCtrlLock.Lock()
	defer o.cmdCtrlLock.Unlock()
	err := o.binaryUpgrade.Upgrade(version)
	if err != nil {
		return false, err.Error()
	}
	return true, ""
}

func ( o * Server ) SelfUpgrade ( version string , bindiff , checksum [ ] byte ) ( bool , string ) { o . cmdCtrlLock . Lock ( ) defer o . cmdCtrlLock . Unlock ( ) err := o . binaryUpgrade . Upgrade ( version ) if err != nil { return false , err . Error ( ) } return true , " " }

// SelfUpgrade deploys an updated binary to disk using cmdctrl.GithubUpdater

SelfUpgrade deploys an updated binary to disk using cmdctrl . GithubUpdater


func (o *Server) SoftwareVersion() string {
	o.cmdCtrlLock.RLock()
	defer o.cmdCtrlLock.RUnlock()
	return o.binaryUpgrade.GetCurrentVersion()
}

func ( o * Server ) SoftwareVersion ( ) string { o . cmdCtrlLock . RLock ( ) defer o . cmdCtrlLock . RUnlock ( ) return o . binaryUpgrade . GetCurrentVersion ( ) }

// SoftwareVersion returns the version of the currently running instance


func (stor *groupStore) Shutdown(ctx context.Context) error {
	stor.lock.Lock()
	err := stor.shutdown()
	stor.lock.Unlock()
	return err
}

func ( stor * groupStore ) Shutdown ( ctx context . Context ) error { stor . lock . Lock ( ) err := stor . shutdown ( ) stor . lock . Unlock ( ) return err }

// Shutdown will close any existing connections; note that Startup may
// automatically get called with any further activity, but it will use a new
// connection. To ensure the groupStore has no further activity, use Close.

Shutdown will close any existing connections ; note that Startup may automatically get called with any further activity but it will use a new connection . To ensure the groupStore has no further activity use Close .


func (c *Client) Rant(rantId int) (RantModel, []CommentModel, error) {
	url := fmt.Sprintf(RANT_PATH, API, rantId, APP_VERSION)
	res, err := http.Get(url)
	if err != nil {
		return RantModel{}, nil, err
	}
	var data RantResponse
	json.NewDecoder(res.Body).Decode(&data)
	if !data.Success && data.Error != "" {
		return RantModel{}, nil, errors.New(data.Error)
	}
	return data.Rant, data.Comments, nil
}

func ( c * Client ) Rant ( rantId int ) ( RantModel , [ ] CommentModel , error ) { url := fmt . Sprintf ( RANT_PATH , API , rantId , APP_VERSION ) res , err := http . Get ( url ) if err != nil { return RantModel { } , nil , err } var data RantResponse json . NewDecoder ( res . Body ) . Decode ( & data ) if ! data . Success && data . Error != " " { return RantModel { } , nil , errors . New ( data . Error ) } return data . Rant , data . Comments , nil }

// Fetches a rant and its comments given a valid rant id


func (c *Client) Profile(username string) (UserModel, ContentModel, error) {
	userId, err := getUserId(username)
	if err != nil {
		return UserModel{}, ContentModel{}, err
	}
	url := fmt.Sprintf(USER_PATH, API, userId, APP_VERSION)
	res, err := http.Get(url)
	if err != nil {
		return UserModel{}, ContentModel{}, err
	}
	var data UserResponse
	json.NewDecoder(res.Body).Decode(&data)
	if !data.Success && data.Error != "" {
		return UserModel{}, ContentModel{}, errors.New(data.Error)
	}
	return data.Profile, data.Profile.Content.Content, nil
}

func ( c * Client ) Profile ( username string ) ( UserModel , ContentModel , error ) { userId , err := getUserId ( username ) if err != nil { return UserModel { } , ContentModel { } , err } url := fmt . Sprintf ( USER_PATH , API , userId , APP_VERSION ) res , err := http . Get ( url ) if err != nil { return UserModel { } , ContentModel { } , err } var data UserResponse json . NewDecoder ( res . Body ) . Decode ( & data ) if ! data . Success && data . Error != " " { return UserModel { } , ContentModel { } , errors . New ( data . Error ) } return data . Profile , data . Profile . Content . Content , nil }


func (c *Client) Search(term string) ([]RantModel, error) {
	url := fmt.Sprintf(SEARCH_PATH, API, term, APP_VERSION)
	res, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	var data SearchResponse
	json.NewDecoder(res.Body).Decode(&data)
	if !data.Success && data.Error != "" {
		return nil, errors.New(data.Error)
	}
	return data.Rants, nil
}

func ( c * Client ) Search ( term string ) ( [ ] RantModel , error ) { url := fmt . Sprintf ( SEARCH_PATH , API , term , APP_VERSION ) res , err := http . Get ( url ) if err != nil { return nil , err } var data SearchResponse json . NewDecoder ( res . Body ) . Decode ( & data ) if ! data . Success && data . Error != " " { return nil , errors . New ( data . Error ) } return data . Rants , nil }

// Search for rants matching the search term


func (c *Client) Surprise() (RantModel, error) {
	url := fmt.Sprintf(SURPRISE_PATH, API, APP_VERSION)
	res, err := http.Get(url)
	if err != nil {
		return RantModel{}, err
	}
	var data RantResponse
	json.NewDecoder(res.Body).Decode(&data)
	if !data.Success && data.Error != "" {
		return RantModel{}, errors.New(data.Error)
	}
	return data.Rant, nil
}

func ( c * Client ) Surprise ( ) ( RantModel , error ) { url := fmt . Sprintf ( SURPRISE_PATH , API , APP_VERSION ) res , err := http . Get ( url ) if err != nil { return RantModel { } , err } var data RantResponse json . NewDecoder ( res . Body ) . Decode ( & data ) if ! data . Success && data . Error != " " { return RantModel { } , errors . New ( data . Error ) } return data . Rant , nil }


func (c *Client) WeeklyRants() ([]RantModel, error) {
	url := fmt.Sprintf(WEEKLY_PATH, API, APP_VERSION)
	res, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	var data RantsResponse
	json.NewDecoder(res.Body).Decode(&data)
	if !data.Success && data.Error != "" {
		return nil, errors.New(data.Error)
	}
	return data.Rants, nil
}

func ( c * Client ) WeeklyRants ( ) ( [ ] RantModel , error ) { url := fmt . Sprintf ( WEEKLY_PATH , API , APP_VERSION ) res , err := http . Get ( url ) if err != nil { return nil , err } var data RantsResponse json . NewDecoder ( res . Body ) . Decode ( & data ) if ! data . Success && data . Error != " " { return nil , errors . New ( data . Error ) } return data . Rants , nil }

// Returns the rants tagged for 'weekly'


func getUserId(username string) (int, error) {
	url := fmt.Sprintf(USER_ID_PATH, API, username, APP_VERSION)
	res, err := http.Get(url)
	if err != nil {
		return 0, err
	}
	var data GetUserIdResponse
	json.NewDecoder(res.Body).Decode(&data)
	if !data.Success && data.Error != "" {
		return 0, errors.New(data.Error)
	}
	return data.UserId, nil
}

func getUserId ( username string ) ( int , error ) { url := fmt . Sprintf ( USER_ID_PATH , API , username , APP_VERSION ) res , err := http . Get ( url ) if err != nil { return 0 , err } var data GetUserIdResponse json . NewDecoder ( res . Body ) . Decode ( & data ) if ! data . Success && data . Error != " " { return 0 , errors . New ( data . Error ) } return data . UserId , nil }

// Fetches the userId given a valid username


func (rs *ReplValueStore) Shutdown(ctx context.Context) error {
	rs.ringLock.Lock()
	if rs.ringServerExitChan != nil {
		close(rs.ringServerExitChan)
		rs.ringServerExitChan = nil
	}
	rs.storesLock.Lock()
	for addr, stc := range rs.stores {
		if err := stc.store.Shutdown(ctx); err != nil {
			rs.logDebug("replValueStore: error during shutdown of store %s: %s", addr, err)
		}
		delete(rs.stores, addr)
		select {
		case <-ctx.Done():
			rs.storesLock.Unlock()
			return ctx.Err()
		default:
		}
	}
	rs.storesLock.Unlock()
	rs.ringLock.Unlock()
	return nil
}

func ( rs * ReplValueStore ) Shutdown ( ctx context . Context ) error { rs . ringLock . Lock ( ) if rs . ringServerExitChan != nil { close ( rs . ringServerExitChan ) rs . ringServerExitChan = nil } rs . storesLock . Lock ( ) for addr , stc := range rs . stores { if err := stc . store . Shutdown ( ctx ) ; err != nil { rs . logDebug ( " " , addr , err ) } delete ( rs . stores , addr ) select { case <- ctx . Done ( ) : rs . storesLock . Unlock ( ) return ctx . Err ( ) default : } } rs . storesLock . Unlock ( ) rs . ringLock . Unlock ( ) return nil }

// Shutdown will close all connections to backend stores and shutdown any
// running ring service connector. Note that the ReplValueStore can still be
// used after Shutdown, it will just start reconnecting to backends again. To
// relaunch the ring service connector, you will need to call Startup.

Shutdown will close all connections to backend stores and shutdown any running ring service connector . Note that the ReplValueStore can still be used after Shutdown it will just start reconnecting to backends again . To relaunch the ring service connector you will need to call Startup .


func FExists(name string) bool {
	if _, err := os.Stat(name); os.IsNotExist(err) {
		return false
	}
	return true
}

func FExists ( name string ) bool { if _ , err := os . Stat ( name ) ; os . IsNotExist ( err ) { return false } return true }


func (m *MessageStream) outbound() {
	for {
		select {
		case <-m.Shutdown:
			log.Infof("Closing OpenFlow message stream.")
			m.conn.Close()
			return
		case msg := <-m.Outbound:
			// Forward outbound messages to conn
			data, _ := msg.MarshalBinary()
			if _, err := m.conn.Write(data); err != nil {
				log.Warnln("OutboundError:", err)
				m.Error <- err
				m.Shutdown <- true
			}

			log.Debugf("Sent(%d): %v", len(data), data)
		}
	}
}

func
(
m
*
MessageStream
)
outbound
(
)
{
for
{
select
{
case
<-
m
.
Shutdown
:
log
.
Infof
(
"
"
)
m
.
conn
.
Close
(
)
return
case
msg
:=
<-
m
.
Outbound
:
// Forward outbound messages to conn
data
,
_
:=
msg
.
MarshalBinary
(
)
if
_
,
err
:=
m
.
conn
.
Write
(
data
)
;
err
!=
{
log
.
Warnln
(
"
"
,
err
)
m
.
Error
<-
err
m
.
Shutdown
<-
true
}
log
.
Debugf
(
"
"
,
len
(
data
)
,
data
)
}
}
}

// Listen for a Shutdown signal or Outbound messages.

Listen for a Shutdown signal or Outbound messages .


func (m *MessageStream) parse() {
	for {
		b := <-m.pool.Full
		log.Debugf("Rcvd: %v", b.Bytes())
		msg, err := m.parser.Parse(b.Bytes())
		// Log all message parsing errors.
		if err != nil {
			log.Print(err)
		}

		m.Inbound <- msg
		b.Reset()
		m.pool.Empty <- b
	}
}

func
(
m
*
MessageStream
)
parse
(
)
{
for
{
b
:=
<-
m
.
pool
.
Full
log
.
Debugf
(
"
"
,
b
.
Bytes
(
)
)
msg
,
err
:=
m
.
parser
.
Parse
(
b
.
Bytes
(
)
)
// Log all message parsing errors.
if
err
!=
{
log
.
Print
(
err
)
}
m
.
Inbound
<-
msg
b
.
Reset
(
)
m
.
pool
.
Empty
<-
b
}
}


func (dom *Domain) Group(name string, members []*Account) *Group {
	return &Group{Domain: dom, Name: name, Members: members}
}

func ( dom * Domain ) Group ( name string , members [ ] * Account ) * Group { return & Group { Domain : dom , Name : name , Members : members } }

// Group creates a Group type from a domain, with the given name and members

Group creates a Group type from a domain with the given name and members


func (dom *Domain) Groups() ([]*Group, error) {
	var vl valueList
	err := dom.cgp.request(listGroups{Domain: dom.Name}, &vl)
	if err != nil {
		return []*Group{}, err
	}
	vals := vl.compact()
	grps := make([]*Group, len(vals))
	for i, v := range vals {
		g, err := dom.GetGroup(v)
		if err != nil {
			return grps, err
		}
		grps[i] = g
	}
	return grps, nil
}

func ( dom * Domain ) Groups ( ) ( [ ] * Group , error ) { var vl valueList err := dom . cgp . request ( listGroups { Domain : dom . Name } , & vl ) if err != nil { return [ ] * Group { } , err } vals := vl . compact ( ) grps := make ( [ ] * Group , len ( vals ) ) for i , v := range vals { g , err := dom . GetGroup ( v ) if err != nil { return grps , err } grps [ i ] = g } return grps , nil }


func (dom *Domain) GetGroup(name string) (*Group, error) {
	var d dictionary
	err := dom.cgp.request(getGroup{Name: fmt.Sprintf("%s@%s", name, dom.Name)}, &d)
	if err != nil {
		return &Group{}, err
	}
	memStr := d.toMap()["Members"]
	var mems []*Account
	dec := xml.NewDecoder(bytes.NewBufferString(memStr))
	for {
		var a string
		err := dec.Decode(&a)
		if err == io.EOF {
			break
		}
		if err != nil {
			return dom.Group(name, mems), err
		}
		if a == "" {
			continue
		}
		mems = append(mems, dom.Account(a))
	}
	return dom.Group(name, mems), nil
}

func ( dom * Domain ) GetGroup ( name string ) ( * Group , error ) { var d dictionary err := dom . cgp . request ( getGroup { Name : fmt . Sprintf ( " " , name , dom . Name ) } , & d ) if err != nil { return & Group { } , err } memStr := d . toMap ( ) [ " " ] var mems [ ] * Account dec := xml . NewDecoder ( bytes . NewBufferString ( memStr ) ) for { var a string err := dec . Decode ( & a ) if err == io . EOF { break } if err != nil { return dom . Group ( name , mems ) , err } if a == " " { continue } mems = append ( mems , dom . Account ( a ) ) } return dom . Group ( name , mems ) , nil }

// GetGroup retrieves a group from a domain with the given group name