/*
RegisterService handles service registartion with Piazza for external services.
*/
968544
func RegisterService(m ResourceMetadata) error {
	data, err := json.Marshal(m)
	if err != nil {
		return errors.New("Error marshaling ResourceMetadata")
	}

	str := fmt.Sprintf("{\"apiKey\":\"my-api-key-38n987\",\"jobType\":{\"type\":\"register-service\",\"data\":%s}}", bytes.NewBuffer(data))
	fmt.Println(str)

	var buffer bytes.Buffer
	w := multipart.NewWriter(&buffer)
	err = w.WriteField("body", str)
	if err != nil {
		return errors.New("Error writing body")
	}
	err = w.Close()
	if err != nil {
		return errors.New("Error closing writer")
	}

	req, err := http.NewRequest("POST", GatewayJobURL, &buffer)
	if err != nil {
		return errors.New("Error creating request")
	}
	req.Header.Add("Content-Type", w.FormDataContentType())

	client := &http.Client{}
	response, err := client.Do(req)
	if err != nil {
		return errors.New("Error performing request")
	}

	if response.Body == nil {
		return errors.New("No JSON body returned from gateway")
	}
	defer response.Body.Close()

	b, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return errors.New("Error reading JSON body returned from gateway")
	}

	var rm JobMsg
	if err := json.Unmarshal(b, &rm); err != nil {
		return errors.New("Error unmarshaling JobMsg")
	}
	log.Println("Gateway received type " + rm.Type + ", jobId " + rm.JobID)

	return nil
}
1162501
func registerService(name string, port int, ttl int) {

	reportInterval := make(chan bool, 1)
	go func() {
		for {
			time.Sleep(time.Duration(ttl) / 2 * time.Second)
			reportInterval <- true
		}
	}()

	client, err := consul.NewClient(consul.DefaultConfig())
	if nil != err {
		log.Error("Failed to get consul client")
	}
	agent := client.Agent()

	serviceRegister(name, port, ttl, agent)
	for {
		select {
		case <-reportInterval: //report registration
			{
				servicePassing(name, agent)

			}
		}
	}

}
1269014
func (c *ServiceClient) serviceRegs(ops *operations, service *structs.Service, task *TaskServices) (
	*ServiceRegistration, error) {

	// Get the services ID
	id := makeTaskServiceID(task.AllocID, task.Name, service, task.Canary)
	sreg := &ServiceRegistration{
		serviceID: id,
		checkIDs:  make(map[string]struct{}, len(service.Checks)),
	}

	// Service address modes default to auto
	addrMode := service.AddressMode
	if addrMode == "" {
		addrMode = structs.AddressModeAuto
	}

	// Determine the address to advertise based on the mode
	ip, port, err := getAddress(addrMode, service.PortLabel, task.Networks, task.DriverNetwork)
	if err != nil {
		return nil, fmt.Errorf("unable to get address for service %q: %v", service.Name, err)
	}

	// Determine whether to use tags or canary_tags
	var tags []string
	if task.Canary && len(service.CanaryTags) > 0 {
		tags = make([]string, len(service.CanaryTags))
		copy(tags, service.CanaryTags)
	} else {
		tags = make([]string, len(service.Tags))
		copy(tags, service.Tags)
	}

	// Build the Consul Service registration request
	serviceReg := &api.AgentServiceRegistration{
		ID:      id,
		Name:    service.Name,
		Tags:    tags,
		Address: ip,
		Port:    port,
		// This enables the consul UI to show that Nomad registered this service
		Meta: map[string]string{
			"external-source": "nomad",
		},
	}
	ops.regServices = append(ops.regServices, serviceReg)

	// Build the check registrations
	checkIDs, err := c.checkRegs(ops, id, service, task)
	if err != nil {
		return nil, err
	}
	for _, cid := range checkIDs {
		sreg.checkIDs[cid] = struct{}{}
	}
	return sreg, nil
}
338433
func RegisterAccountServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
	return RegisterAccountServiceHandlerClient(ctx, mux, NewAccountServiceClient(conn))
}
494174
func SyncServiceRegistry(conn client.Connection, request ServiceRegistrySyncRequest) error {
	logger := plog.WithField("serviceid", request.ServiceID)

	if len(request.PortsToDelete) == 0 &&
	   len(request.PortsToPublish) == 0 &&
	   len(request.VHostsToDelete) == 0 &&
	   len(request.VHostsToPublish) == 0 {
		// Don't even create a transaction if there's nothing to do (which is typical for many kinds of services)
		return nil
	}

	tx := conn.NewTransaction()

	if err := syncServicePublicPorts(conn, tx, request); err != nil {
		logger.WithError(err).Debug("Could not sync public ports for service")
		return err
	}
	if err := syncServiceVHosts(conn, tx, request); err != nil {
		logger.WithError(err).Debug("Could not sync virtual hosts for service")
		return err
	}

	if err := tx.Commit(); err != nil {
		logger.WithError(err).Debug("Could not sync registry for service")
		// TODO: wrap error?
		return err
	}

	logger.Debug("Updated registry for service")
	return nil
}
10676
func RegisterService(m ResourceMetadata) error {
	data, err := json.Marshal(m)
	if err != nil {
		return errors.New("Error marshaling ResourceMetadata")
	}

	response, err := http.Post(
		RegistryURL, ContentTypeJSON, bytes.NewBuffer(data),
	)
	if err != nil {
		return errors.New("Error posting ResourceMetadata to registerService")
	}

	if response.Body == nil {
		return errors.New("No JSON body returned from registerService")
	}

	b, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return errors.New("Error reading JSON body returned from registerService")
	}

	// Throw 400 if we cannot unmarshal the body as a valid InputMsg.
	var rm RegisterServiceMsg
	if err := json.Unmarshal(b, &rm); err != nil {
		return errors.New("Error unmarshaling RegisterServiceMsg")
	}
	log.Println("RegisterService received resourceId=" + rm.ResourceID)

	return nil
}
930296
func RegisterResponseBodyServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
	return RegisterResponseBodyServiceHandlerClient(ctx, mux, NewResponseBodyServiceClient(conn))
}
870507
func RegisterSettingsServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
	return RegisterSettingsServiceHandlerClient(ctx, mux, NewSettingsServiceClient(conn))
}
175181
func (ec *ServiceManager) BindService(service RunnableInterface) {
	ec.services = append(ec.services, service)
}
1264689
func (s *EnvoyApi) registrationHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
	defer req.Body.Close()

	response.Header().Set("Content-Type", "application/json")

	name, ok := params["service"]
	if !ok {
		log.Debug("No service name provided to Envoy registrationHandler")
		sendJsonError(response, 404, "Not Found - No service name provided")
		return
	}

	svcName, svcPort, err := SvcNameSplit(name)
	if err != nil {
		log.Debugf("Envoy Service '%s' not found in registrationHandler: %s", name, err)
		sendJsonError(response, 404, "Not Found - "+err.Error())
		return
	}

	instances := make([]*EnvoyService, 0)
	// Enter critical section
	func() {
		s.state.RLock()
		defer s.state.RUnlock()
		s.state.EachService(func(hostname *string, id *string, svc *service.Service) {
			if svc.Name == svcName && svc.IsAlive() {
				newInstance := s.EnvoyServiceFromService(svc, svcPort)
				if newInstance != nil {
					instances = append(instances, newInstance)
				}
			}
		})
	}()

	clusterName := ""
	if s.list != nil {
		clusterName = s.list.ClusterName()
	}

	result := SDSResult{
		Env:     clusterName,
		Hosts:   instances,
		Service: name,
	}

	jsonBytes, err := result.MarshalJSON()
	defer ffjson.Pool(jsonBytes)
	if err != nil {
		log.Errorf("Error marshaling state in registrationHandler: %s", err.Error())
		sendJsonError(response, 500, "Internal server error")
		return
	}

	response.Write(jsonBytes)
}
81728
func (ep *EtcdClient) RegisterService(serviceInfo ServiceInfo) error {
	keyName := "/contiv.io/service/" + serviceInfo.ServiceName + "/" +
		serviceInfo.HostAddr + ":" + strconv.Itoa(serviceInfo.Port)
	ttl := time.Duration(serviceInfo.TTL) * time.Second

	log.Infof("Registering service key: %s, value: %+v", keyName, serviceInfo)

	// if there is a previously registered service, stop refreshing it
	if ep.serviceDb[keyName] != nil {
		ep.serviceDb[keyName].stopChan <- true
	}

	// JSON format the object
	jsonVal, err := json.Marshal(serviceInfo)
	if err != nil {
		log.Errorf("Json conversion error. Err %v", err)
		return err
	}

	// create service state
	srvState := etcdServiceState{
		ServiceName: serviceInfo.ServiceName,
		KeyName:     keyName,
		TTL:         ttl,
		HostAddr:    serviceInfo.HostAddr,
		Port:        serviceInfo.Port,
		stopChan:    make(chan bool, 1),
		Hostname:    serviceInfo.Hostname,
	}

	// Run refresh in background
	go ep.refreshService(&srvState, string(jsonVal[:]))

	// Store it in DB
	ep.serviceDb[keyName] = &srvState

	return nil
}
971027
func Register() {
	registerMetrics.Do(func() {
		prometheus.MustRegister(CRIOOperations)
		prometheus.MustRegister(CRIOOperationsLatency)
		prometheus.MustRegister(CRIOOperationsErrors)
	})
}
1163628
func (rs *ReferenceRiskService) RegisterPlugin(plugin plugin.RiskServicePlugin) {
	rs.plugins = append(rs.plugins, plugin)
}
430838
func (d *API) RegisterConsumer(mediaType string, handler runtime.Consumer) {
	if d.consumers == nil {
		d.consumers = make(map[string]runtime.Consumer, 10)
	}
	d.consumers[strings.ToLower(mediaType)] = handler
}
250205
func (s *HTTPServer) registerEnterpriseHandlers() {
	s.mux.HandleFunc("/v1/namespaces", s.wrap(s.entOnly))
	s.mux.HandleFunc("/v1/namespace", s.wrap(s.entOnly))
	s.mux.HandleFunc("/v1/namespace/", s.wrap(s.entOnly))

	s.mux.HandleFunc("/v1/sentinel/policies", s.wrap(s.entOnly))
	s.mux.HandleFunc("/v1/sentinel/policy/", s.wrap(s.entOnly))

	s.mux.HandleFunc("/v1/quotas", s.wrap(s.entOnly))
	s.mux.HandleFunc("/v1/quota-usages", s.wrap(s.entOnly))
	s.mux.HandleFunc("/v1/quota/", s.wrap(s.entOnly))
	s.mux.HandleFunc("/v1/quota", s.wrap(s.entOnly))
}
403225
func (m *serviceMap) register(rcvr interface{}, name string, passReq bool) error {
	// Setup service.
	s := &service{
		name:     name,
		rcvr:     reflect.ValueOf(rcvr),
		rcvrType: reflect.TypeOf(rcvr),
		methods:  make(map[string]*serviceMethod),
		passReq:  passReq,
	}
	if name == "" {
		s.name = reflect.Indirect(s.rcvr).Type().Name()
		if !isExported(s.name) {
			return fmt.Errorf("rpc: type %q is not exported", s.name)
		}
	}
	if s.name == "" {
		return fmt.Errorf("rpc: no service name for type %q",
			s.rcvrType.String())
	}
	// Setup methods.
	for i := 0; i < s.rcvrType.NumMethod(); i++ {
		method := s.rcvrType.Method(i)
		mtype := method.Type

		// offset the parameter indexes by one if the
		// service methods accept an HTTP request pointer
		var paramOffset int
		if passReq {
			paramOffset = 1
		} else {
			paramOffset = 0
		}

		// Method must be exported.
		if method.PkgPath != "" {
			continue
		}
		// Method needs four ins: receiver, *http.Request, *args, *reply.
		if mtype.NumIn() != 3+paramOffset {
			continue
		}

		// If the service methods accept an HTTP request pointer
		if passReq {
			// First argument must be a pointer and must be http.Request.
			reqType := mtype.In(1)
			if reqType.Kind() != reflect.Ptr || reqType.Elem() != typeOfRequest {
				continue
			}
		}
		// Next argument must be a pointer and must be exported.
		args := mtype.In(1 + paramOffset)
		if args.Kind() != reflect.Ptr || !isExportedOrBuiltin(args) {
			continue
		}
		// Next argument must be a pointer and must be exported.
		reply := mtype.In(2 + paramOffset)
		if reply.Kind() != reflect.Ptr || !isExportedOrBuiltin(reply) {
			continue
		}
		// Method needs one out: error.
		if mtype.NumOut() != 1 {
			continue
		}
		if returnType := mtype.Out(0); returnType != typeOfError {
			continue
		}
		s.methods[method.Name] = &serviceMethod{
			method:    method,
			argsType:  args.Elem(),
			replyType: reply.Elem(),
		}
	}
	if len(s.methods) == 0 {
		return fmt.Errorf("rpc: %q has no exported methods of suitable type",
			s.name)
	}
	// Add to the map.
	m.mutex.Lock()
	defer m.mutex.Unlock()
	if m.services == nil {
		m.services = make(map[string]*service)
	} else if _, ok := m.services[s.name]; ok {
		return fmt.Errorf("rpc: service already defined: %q", s.name)
	}
	m.services[s.name] = s
	return nil
}
228140
func (r *RemoteService) Register(comp component.Component, opts []component.Option) error {
	s := component.NewService(comp, opts)

	if _, ok := r.services[s.Name]; ok {
		return fmt.Errorf("remote: service already defined: %s", s.Name)
	}

	if err := s.ExtractRemote(); err != nil {
		return err
	}

	r.services[s.Name] = s
	// register all remotes
	for name, remote := range s.Remotes {
		remotes[fmt.Sprintf("%s.%s", s.Name, name)] = remote
	}

	return nil
}