<commit_before>// Copyright © 2016 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

package core

import (
	"crypto/tls"
	"fmt"
	"net/http"
	"runtime"
	"sync/atomic"
	"time"

	pb_discovery "github.com/TheThingsNetwork/ttn/api/discovery"
	pb_noc "github.com/TheThingsNetwork/ttn/api/noc"
	"github.com/TheThingsNetwork/ttn/utils/errors"
	"github.com/TheThingsNetwork/ttn/utils/logging"
	"github.com/TheThingsNetwork/ttn/utils/security"
	"github.com/TheThingsNetwork/ttn/utils/tokenkey"
	"github.com/apex/log"
	"github.com/dgrijalva/jwt-go"
	"github.com/mwitkow/go-grpc-middleware"
	"github.com/spf13/viper"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/peer"
)

type ComponentInterface interface {
	RegisterRPC(s *grpc.Server)
	Init(c *Component) error
	ValidateNetworkContext(ctx context.Context) (*pb_discovery.Announcement, error)
	ValidateTTNAuthContext(ctx context.Context) (*TTNClaims, error)
}

type ManagementInterface interface {
	RegisterManager(s *grpc.Server)
}

// NewComponent creates a new Component
func NewComponent(ctx log.Interface, serviceName string, announcedAddress string) (*Component, error) {
	go func() {
		memstats := new(runtime.MemStats)
		for range time.Tick(time.Minute) {
			runtime.ReadMemStats(memstats)
			ctx.WithFields(log.Fields{
				"Goroutines": runtime.NumGoroutine(),
				"Memory":     float64(memstats.Alloc) / 1000000,
			}).Debugf("Stats")
		}
	}()

	grpclog.SetLogger(logging.NewGRPCLogger(ctx))

	component := &Component{
		Ctx: ctx,
		Identity: &pb_discovery.Announcement{
			Id:             viper.GetString("id"),
			Description:    viper.GetString("description"),
			ServiceName:    serviceName,
			ServiceVersion: fmt.Sprintf("%s-%s (%s)", viper.GetString("version"), viper.GetString("gitCommit"), viper.GetString("buildDate")),
			NetAddress:     announcedAddress,
		},
		AccessToken: viper.GetString("auth-token"),
		TokenKeyProvider: tokenkey.NewHTTPProvider(
			viper.GetStringMapString("auth-servers"),
			viper.GetString("key-dir"),
		),
	}

	if serviceName != "discovery" {
		var err error
		component.Discovery, err = pb_discovery.NewClient(
			viper.GetString("discovery-server"),
			component.Identity,
			func() string {
				token, _ := component.BuildJWT()
				return token
			},
		)
		if err != nil {
			return nil, err
		}
	}

	if pub, priv, cert, err := security.LoadKeys(viper.GetString("key-dir")); err == nil {<commit_msg>Replace tokenkey by go-account-lib equivalent<commit_after>// Copyright © 2016 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

package core

import (
	"crypto/tls"
	"fmt"
	"net/http"
	"runtime"
	"sync/atomic"
	"time"

	"github.com/TheThingsNetwork/go-account-lib/tokenkey"
	"github.com/TheThingsNetwork/go-account-lib/tokenkey/cache"
	pb_discovery "github.com/TheThingsNetwork/ttn/api/discovery"
	pb_noc "github.com/TheThingsNetwork/ttn/api/noc"
	"github.com/TheThingsNetwork/ttn/utils/errors"
	"github.com/TheThingsNetwork/ttn/utils/logging"
	"github.com/TheThingsNetwork/ttn/utils/security"
	"github.com/apex/log"
	"github.com/dgrijalva/jwt-go"
	"github.com/mwitkow/go-grpc-middleware"
	"github.com/spf13/viper"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/peer"
)

type ComponentInterface interface {
	RegisterRPC(s *grpc.Server)
	Init(c *Component) error
	ValidateNetworkContext(ctx context.Context) (*pb_discovery.Announcement, error)
	ValidateTTNAuthContext(ctx context.Context) (*TTNClaims, error)
}

type ManagementInterface interface {
	RegisterManager(s *grpc.Server)
}

// NewComponent creates a new Component
func NewComponent(ctx log.Interface, serviceName string, announcedAddress string) (*Component, error) {
	go func() {
		memstats := new(runtime.MemStats)
		for range time.Tick(time.Minute) {
			runtime.ReadMemStats(memstats)
			ctx.WithFields(log.Fields{
				"Goroutines": runtime.NumGoroutine(),
				"Memory":     float64(memstats.Alloc) / 1000000,
			}).Debugf("Stats")
		}
	}()

	grpclog.SetLogger(logging.NewGRPCLogger(ctx))

	component := &Component{
		Ctx: ctx,
		Identity: &pb_discovery.Announcement{
			Id:             viper.GetString("id"),
			Description:    viper.GetString("description"),
			ServiceName:    serviceName,
			ServiceVersion: fmt.Sprintf("%s-%s (%s)", viper.GetString("version"), viper.GetString("gitCommit"), viper.GetString("buildDate")),
			NetAddress:     announcedAddress,
		},
		AccessToken: viper.GetString("auth-token"),
		TokenKeyProvider: tokenkey.HTTPProvider(
			viper.GetStringMapString("auth-servers"),
			cache.WriteTroughCache(viper.GetString("key-dir")),
		),
	}

	if serviceName != "discovery" {
		var err error
		component.Discovery, err = pb_discovery.NewClient(
			viper.GetString("discovery-server"),
			component.Identity,
			func() string {
				token, _ := component.BuildJWT()
				return token
			},
		)
		if err != nil {
			return nil, err
		}
	}

	if pub, priv, cert, err := security.LoadKeys(viper.GetString("key-dir")); err == nil {
{'fraction_non_alphanumeric': 0.13979303857008465, 'fraction_numerical': 0.005644402634054563, 'mean_word_length': 4.503105590062112, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3170561', 'n_tokens_mistral': 1989, 'n_tokens_neox': 1847, 'n_words': 327}