// Spawn manages a specific vhost for a subdomain
357491
func (l *VHostListener) Spawn(shutdown <-chan interface{}, subdomain string) {
	logger := plog.WithFields(log.Fields{
		"hostid":    l.hostID,
		"subdomain": subdomain,
	})

	// keep a cache of exports that have already been
	// looked up.
	exportMap := make(map[string]ExportDetails)

	// keep track of the on/off state of the export
	isEnabled := false
	defer func() {
		if isEnabled {
			l.handler.Disable(subdomain)
			logger.Debug("Disabled virtual host")
		}
	}()

	done := make(chan struct{})
	defer func() { close(done) }()
	for {

		// set up a watch on the vhost
		pth := l.GetPath(subdomain)
		dat := &VHost{}
		evt, err := l.conn.GetW(pth, dat, done)
		if err == client.ErrNoNode {
			logger.Debug("Virtual host was deleted, exiting")
			return
		} else if err != nil {
			logger.WithError(err).Error("Could not watch subdomain")
			return
		}

		// track the exports
		exLogger := logger.WithFields(log.Fields{
			"tenantid":    dat.TenantID,
			"application": dat.Application,
		})

		var exevt <-chan client.Event
		var ch []string

		expth := path.Join("/net/export", dat.TenantID, dat.Application)

		// keep checking until we have an event or an error
		for {
			var ok bool
			var err error

			ok, exevt, err = l.conn.ExistsW(expth, done)
			if err != nil {
				exLogger.WithError(err).Error("Could not check exports for endpoint")
				return
			}

			if ok {
				ch, exevt, err = l.conn.ChildrenW(expth, done)
				if err == client.ErrNoNode {
					logger.Debug("VHost suddenly deleted, retrying")
					close(done)
					done = make(chan struct{})

					// we need an event, so try again
					continue
				} else if err != nil {
					exLogger.WithFields(log.Fields{
						"Error": err,
					}).Error("Could not track exports for endpoint")
					return
				}
			}
			break
		}

		exports := []ExportDetails{}

		// get the exports and update the cache
		sendUpdate := len(ch) != len(exportMap)
		chMap := make(map[string]ExportDetails)
		for _, name := range ch {
			export, ok := exportMap[name]
			if !ok {
				sendUpdate = true
				if err := l.conn.Get(path.Join(expth, name), &export); err == client.ErrNoNode {
					continue
				} else if err != nil {
					exLogger.WithField("exportkey", name).WithError(err).Error("Could not look up export")
					return
				}
			}
			chMap[name] = export
			exports = append(exports, export)
		}

		exportMap = chMap

		// only send an update if the exports have changed
		if sendUpdate {
			l.handler.Set(subdomain, exports)
		}

		// do something if the state of the vhost has changed
		if !isEnabled {
			l.handler.Enable(subdomain)
			logger.Debug("Enabled vhost")
			isEnabled = true
		}

		select {
		case <-evt:
		case <-exevt:
		case <-shutdown:
			return
		}

		close(done)
		done = make(chan struct{})
	}
}
486247
func (c *Context) SubURLRedirect(location string, status ...int) {
	c.Redirect(setting.AppSubURL+location, status...)
}
929764
func (httpsender *HTTPSender) Spawn(id int) utils.Composer {
	s := *httpsender
	s.id = id

	if httpsender.Config.Logger == nil {
		s.logger = logrus.NewEntry(logrus.New())
		s.logger.Logger.Out = ioutil.Discard
	} else {
		s.logger = httpsender.Config.Logger.WithFields(logrus.Fields{
			"worker": id,
		})
	}

	if httpsender.Debug {
		s.logger.Logger.Level = logrus.DebugLevel
	}

	s.logger.Debugf("Spawning worker")

	if govalidator.IsURL(s.URL) {
		s.Client = new(http.Client)

		if httpsender.Config.Insecure {
			s.Client.Transport = &http.Transport{
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			}
		}
	} else {
		s.err = errors.New("Invalid URL")
	}

	return &s
}
985708
func (s *Server) Generate() error {
	s.Resources = getAllResources(s.APIDef, true)

	if err := generateAllObjects(s.APIDef, s.Dir); err != nil {
		return err
	}

	// main file
	if err := s.generateMain(); err != nil {
		return err
	}

	// API implementation
	if err := generateResourceAPIs(s.Resources, s.Dir); err != nil {
		return err
	}

	// security related files
	if err := s.generateSecurity(); err != nil {
		return err
	}

	// HTML front page
	if err := commons.GenerateFile(s, "./templates/index.html.tmpl", "index.html", filepath.Join(s.Dir, "index.html"), false); err != nil {
		return err
	}

	return nil
}
598291
func (srv *Server) Serve(l net.Listener) error {
	// Spawn a shadow http.Server to do the actual servering. We do this
	// because we need to sketch on some of the parameters you passed in,
	// and it's nice to keep our sketching to ourselves.
	shadow := *(*http.Server)(srv)

	if shadow.ReadTimeout == 0 {
		shadow.ReadTimeout = forever
	}
	shadow.Handler = middleware(shadow.Handler)

	wrap := listener.Wrap(l, listener.Deadline)
	appendListener(wrap)

	err := shadow.Serve(wrap)
	return peacefulError(err)
}
1254517
func (l *Synchronizer) Spawn(shutdown <-chan interface{}, nodeID string) {
	// Start dependent listeners
	var (
		wg        sync.WaitGroup
		_shutdown = make(chan interface{})
		stopping  = make(chan interface{})
	)

	defer func() {
		close(_shutdown)
		wg.Wait()
	}()

	var id string
	var wait <-chan time.Time
	done := make(chan struct{})
	defer func(channel *chan struct{}) { close(*channel) }(&done)
	for {
		node := l.Allocate()
		event, err := l.conn.GetW(l.GetPath(nodeID), node, done)
		if err == client.ErrNoNode && id != "" {
			if err := l.Delete(id); err != nil {
				glog.Errorf("Could not delete node at %s: %s", l.GetPath(nodeID), err)
				wait = time.After(DefaultRetryTime)
			} else {
				return
			}
		} else if err != nil {
			glog.Errorf("Could not get node at %s: %s", l.GetPath(nodeID), err)
			return
		}

		if key, err := l.AddUpdate(id, node); err == ErrInvalidType {
			glog.Errorf("Invalid type detected")
			return
		} else if err != nil {
			glog.Errorf("Could not update node at %s: %s", l.GetPath(nodeID), err)
			wait = time.After(DefaultRetryTime)
		} else if id == "" {
			wg.Add(1)
			go func() {
				defer wg.Done()
				if len(l.lfuncs) == 0 {
					return
				}
				defer close(stopping)
				l.startListeners(_shutdown, nodeID)
			}()
			id = key
		}

		select {
		case <-event:
		case <-wait:
		case <-stopping:
			return
		case <-shutdown:
			return
		}

		close(done)
		done = make(chan struct{})
	}
}
197475
func (cmd *MoveAllocationCommand) Source() (interface{}, error) {
	source := make(map[string]interface{})
	source["index"] = cmd.index
	source["shard"] = cmd.shardId
	source["from_node"] = cmd.fromNode
	source["to_node"] = cmd.toNode
	return source, nil
}
175333
func (l *RegistryListener) Spawn(shutdown <-chan interface{}, id string) {
	imagepath := l.GetPath(id)
	done := make(chan struct{})
	defer func(channel *chan struct{}) { close(*channel) }(&done)
	for {
		// Get the node
		var node RegistryImageNode
		evt, err := l.conn.GetW(imagepath, &node, done)
		if err != nil {
			glog.Errorf("Could not look up node at %s: %s", imagepath, err)
			return
		}
		repopath := path.Join(zkregistryrepos, node.Image.Library, node.Image.Repo)
		reponode := &RegistryImageLeader{HostID: l.hostid}
		leader, err := l.conn.NewLeader(repopath)
		if err != nil {
			glog.Errorf("Could not set up leader for %s: %s", repopath, err)
			return
		}
		// Has the image been pushed?
		glog.V(1).Infof("Spawn id=%s node: %s:%s %s", id, node.Image.Repo, node.Image.Tag, node.Image.Tag)
		if node.PushedAt.Unix() == 0 {
			// Do I have the image?
			glog.Infof("Checking if push required for id=%s node: %s:%s %s (UUID=%s)", id, node.Image.Repo, node.Image.Tag, node.Image.Tag, node.Image.UUID)
			if img, err := l.FindImage(&node.Image); err == nil {
				glog.V(1).Infof("Found image %v locally, acquiring lead", node.Image)
				func() {
					// Become the leader so I can push the image
					leaderDone := make(chan struct{})
					defer close(leaderDone)
					_, err := leader.TakeLead(reponode, leaderDone)
					if err != nil {
						glog.Errorf("Could not take lead %s: %s", imagepath, err)
						return
					}
					defer leader.ReleaseLead()
					// Did I shutdown before I got the lead?
					select {
					case <-shutdown:
						return
					default:
						// Did the image change (or get pushed) before I got the lead?
						if err := l.conn.Get(imagepath, &node); err != nil {
							glog.Errorf("Could not get %s: %s", imagepath, err)
							return
						}
						if node.PushedAt.Unix() > 0 {
							glog.V(1).Infof("Image %s already pushed, cancelling push", node.Image.String())
							return
						}
						if img.ID != node.Image.UUID {
							localHash, err := l.docker.GetImageHash(img.ID)
							if err != nil {
								glog.Warningf("Error building hash of image: %s, cancelling push: %s", img.ID, err)
								return
							} else if localHash != node.Image.Hash {
								glog.V(1).Infof("Image %s changed, cancelling push", node.Image.String())
								return
							}
						}
					}
					// Push the image and update the registry
					// If the push is unsuccessful, still update the timestamp,
					// so that the push will get retriggered the next time it
					// is needed.
					registrypath := path.Join(l.address, node.Image.String())
					glog.V(1).Infof("Updating registry image %s from path=%s", img.ID, registrypath)
					if err := l.docker.TagImage(img.ID, registrypath); err != nil {
						glog.Warningf("Could not tag %s as %s: %s", img.ID, registrypath, err)
						node.PushedAt = time.Unix(0, 0)
					} else if err := l.docker.PushImage(registrypath); err != nil {
						glog.Warningf("Could not push %s: %s", registrypath, err)
						node.PushedAt = time.Unix(0, 0)
					} else {
						node.PushedAt = time.Now().UTC()
					}
					// The point here is to make sure the node triggers an
					// event regardless of whether the push was successful.
					l.conn.Set(imagepath, &node)
				}()
			} else {
				glog.Errorf("Could not find image %s: %s", node.Image.UUID, err)
			}
		}
		glog.V(1).Infof("Waiting for image %s to update (imagepath=%s)", node.Image, imagepath)
		select {
		case <-evt:
		case <-shutdown:
			return
		}

		close(done)
		done = make(chan struct{})
	}
}
1046915
func (s *Subdomains) URL(purl string, args ...string) string {
	info := s.Get(args...)
	if info == nil {
		return purl
	}
	if len(info.Host) < 1 {
		if s.Default == info.Name {
			return purl
		}
		return `/` + info.Name + purl
	}
	if len(s.Protocol) < 1 {
		return `http://` + info.Host + purl
	}
	return s.Protocol + `://` + info.Host + purl
}
37167
func (b *serverBuilder) Build() (*ServerBuildResult, error) {

	// start
	b.callEventHandlerIfExists(ServerBuildOnStart)
	b.currentBuildValue = &ServerBuildValue{}
	b.currentBuildResult = &ServerBuildResult{}

	if len(b.errors) > 0 {
		return b.currentBuildResult, b.getFlattenErrors()
	}

	// build parameter
	if err := b.buildParams(); err != nil {
		return b.currentBuildResult, err
	}

	// create server
	b.callEventHandlerIfExists(ServerBuildOnCreateServerBefore)
	if err := b.createServer(); err != nil {
		return b.currentBuildResult, err
	}
	b.callEventHandlerIfExists(ServerBuildOnCreateServerAfter)

	// create disks
	if err := b.createDisks(); err != nil {
		return b.currentBuildResult, err
	}

	if !b.canAutoBoot() {
		// connect exists disks
		if err := b.connectDisks(); err != nil {
			return b.currentBuildResult, err
		}

		// insert cdrom
		if b.isoImageID > 0 {
			b.callEventHandlerIfExists(ServerBuildOnInsertCDROMBefore)
			if err := b.insertCDROM(); err != nil {
				return b.currentBuildResult, err
			}
			b.callEventHandlerIfExists(ServerBuildOnInsertCDROMAfter)
		}

		// connect packet filters
		if err := b.connectPacketFilters(); err != nil {
			return b.currentBuildResult, err
		}

		// boot server
		if b.bootAfterCreate {
			b.callEventHandlerIfExists(ServerBuildOnBootBefore)
			if err := b.bootServer(); err != nil {
				return b.currentBuildResult, err
			}
			b.callEventHandlerIfExists(ServerBuildOnBootAfter)
		}
	}

	if len(b.displayIPAddresses) > 0 {
		for i, nic := range b.currentBuildResult.Server.Interfaces {
			ifID := nic.ID
			displayIP := b.displayIPAddresses[i]
			if displayIP != "" {
				if _, err := b.client.InterfaceSetDisplayIPAddress(ifID, displayIP); err != nil {
					return b.currentBuildResult, err
				}
				// reload server
				server, err := b.client.ServerRead(b.currentBuildResult.Server.ID)
				if err != nil {
					return b.currentBuildResult, err
				}
				b.currentBuildResult.Server = server
			}
		}
	}

	// complete
	b.callEventHandlerIfExists(ServerBuildOnComplete)
	return b.currentBuildResult, nil
}
821692
func (e *Engine) VirtualizationStop(ctx context.Context, ID string) error {
	return e.client.ContainerStop(ctx, ID, nil)
}
784255
func (vm *VM) Halt() error {
	vmclient, err := vm.getVMClient()
	if err != nil {
		return fmt.Errorf(errGetClient, err)
	}

	reqID, err := vmclient.ShutdownRole(vm.ServiceName, vm.Name, vm.Name, virtualmachine.PostShutdownActionStopped)

	if err != nil {
		return err
	}

	// Wait for the shutdown
	if err := client.WaitForOperation(reqID, nil); err != nil {
		return fmt.Errorf("Error waiting for instance %s to be shutting down the hosted service %s: %s",
			vm.Name, vm.Name, err)
	}
	return nil
}
1072438
func (h PfssoHandler) spawnSso(ctx context.Context, firewall firewallsso.FirewallSSOInt, info map[string]string, f func(info map[string]string) (bool, error)) {
	// Perform a copy of the information hash before spawning the goroutine
	infoCopy := map[string]string{}
	for k, v := range info {
		infoCopy[k] = v
	}

	go func() {
		defer panichandler.Standard(ctx)
		sent, err := f(infoCopy)
		if err != nil {
			log.LoggerWContext(ctx).Error(fmt.Sprintf("Error while sending SSO to %s: %s"+firewall.GetFirewallSSO(ctx).PfconfigHashNS, err))
		}

		if sent {
			log.LoggerWContext(ctx).Debug("Sent SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS)
		} else {
			log.LoggerWContext(ctx).Debug("Didn't send SSO to " + firewall.GetFirewallSSO(ctx).PfconfigHashNS)
		}
	}()
}
219232
func (cmd *CancelAllocationCommand) Source() (interface{}, error) {
	source := make(map[string]interface{})
	source["index"] = cmd.index
	source["shard"] = cmd.shardId
	source["node"] = cmd.node
	source["allow_primary"] = cmd.allowPrimary
	return source, nil
}
917532
func (s *SubServer) Start(listenAddr string) error {
	s.listenAddr = listenAddr

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Example notify response
		/*
			Method:NOTIFY URL:/ Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[Nt:[upnp:event] Nts:[upnp:propchange] Sid:[uuid:054ce1c6-1dd2-11b2-864f-d1dbdfd9a2e2] Seq:[6] Content-Type:[text/xml; charset="utf-8"] Content-Length:[296]] Body:0xc4200dc300 ContentLength:296 TransferEncoding:[] Close:false Host:192.168.0.9:9000 Form:map[] PostForm:map[] MultipartForm:<nil> Trailer:map[] RemoteAddr:192.168.0.34:3663 RequestURI:/ TLS:<nil> Cancel:<nil> Response:<nil> ctx:0xc4200dc340}
		*/

		defer func() {
			w.WriteHeader(http.StatusOK)
		}()

		if r.Method != "NOTIFY" {
			return
		}

		sid, ok := r.Header["Sid"]
		if !ok {
			return
		}
		if len(sid) == 0 {
			return
		}
		sub, ok := s.subs[sid[0]]
		if !ok {
			return
		}

		// Just return a string, caller responsible for disassembling it
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			return
		}
		sub.Subscriber.UPNPNotify(NotifyEvent{SID: sid[0], Body: string(body)})
	})

	return http.ListenAndServe(listenAddr, mux)
}
1141521
func (q *ParentIdQuery) Source() (interface{}, error) {
	// {
	//   "parent_id" : {
	//       "type" : "blog",
	//       "id" : "1"
	//   }
	// }
	source := make(map[string]interface{})
	query := make(map[string]interface{})
	source["parent_id"] = query

	query["type"] = q.typ
	query["id"] = q.id
	if q.boost != nil {
		query["boost"] = *q.boost
	}
	if q.ignoreUnmapped != nil {
		query["ignore_unmapped"] = *q.ignoreUnmapped
	}
	if q.queryName != "" {
		query["_name"] = q.queryName
	}
	if q.innerHit != nil {
		src, err := q.innerHit.Source()
		if err != nil {
			return nil, err
		}
		query["inner_hits"] = src
	}
	return source, nil
}
1322831
func (s *Server) Start(ctx context.Context) (*net.TCPAddr, error) {
	return s.srv.Start(ctx, "devshell", s.Port, s.serve)
}