diff --git a/src/config/address.go b/src/config/address.go index ada521245d0427895bff646cffd036314869bae2..13baf5520c2f20a199d3b386f2c6b4415eae1175 100644 --- a/src/config/address.go +++ b/src/config/address.go @@ -32,14 +32,16 @@ type ServerUrl struct { } const ( - MEP_AUTH_APIGW_URL string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/token" - MEP_SER_REGISTER_APIGW_URL string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/mec_service_mgmt/v1/applications/${appInstanceId}/services" - MEP_SER_QUERY_BY_NAME_APIGW_URL string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/mec_service_mgmt/v1/services?ser_name=" - MEP_HEART_BEAT_APIGW_URL string = "https://${MEP_IP}:${MEP_APIGW_PORT}" - MEP_IP string = "${MEP_IP}" - MEP_APIGW_PORT string = "${MEP_APIGW_PORT}" + MepAuthApigwUrl string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/token" + MepSerRegisterApigwUrl string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/mec_service_mgmt/v1/applications/${appInstanceId}/services" + MepSerQueryByNameApigwUrl string = "https://${MEP_IP}:${MEP_APIGW_PORT}/mep/mec_service_mgmt/v1/services?ser_name=" + MepHeartBeatApigwUrl string = "https://${MEP_IP}:${MEP_APIGW_PORT}" + MepIp string = "${MEP_IP}" + MepApigwPort string = "${MEP_APIGW_PORT}" ) +var ServerUrlConfig ServerUrl + // Returns server URL func GetServerUrl() (ServerUrl, error) { @@ -55,19 +57,19 @@ func GetServerUrl() (ServerUrl, error) { } serverUrl.MepServerRegisterUrl = strings.Replace( - strings.Replace(MEP_SER_REGISTER_APIGW_URL, MEP_IP, mepIp, 1), - MEP_APIGW_PORT, mepApiGwPort, 1) + strings.Replace(MepSerRegisterApigwUrl, MepIp, mepIp, 1), + MepApigwPort, mepApiGwPort, 1) serverUrl.MepAuthUrl = strings.Replace( - strings.Replace(MEP_AUTH_APIGW_URL, MEP_IP, mepIp, 1), - MEP_APIGW_PORT, mepApiGwPort, 1) + strings.Replace(MepAuthApigwUrl, MepIp, mepIp, 1), + MepApigwPort, mepApiGwPort, 1) serverUrl.MepHeartBeatUrl = strings.Replace( - strings.Replace(MEP_HEART_BEAT_APIGW_URL, MEP_IP, mepIp, 1), - MEP_APIGW_PORT, mepApiGwPort, 1) + strings.Replace(MepHeartBeatApigwUrl, MepIp, mepIp, 1), + MepApigwPort, mepApiGwPort, 1) serverUrl.MepServiceDiscoveryUrl = strings.Replace( - strings.Replace(MEP_SER_QUERY_BY_NAME_APIGW_URL, MEP_IP, mepIp, 1), - MEP_APIGW_PORT, mepApiGwPort, 1) + strings.Replace(MepSerQueryByNameApigwUrl, MepIp, mepIp, 1), + MepApigwPort, mepApiGwPort, 1) return serverUrl, nil } diff --git a/src/controllers/endpointcontroller.go b/src/controllers/endpointcontroller.go index 2071e170c36d2dea5e2471cdcbc328552dca76b2..b2e5b8740916b64d3141f3b34e16cc418a03b0b7 100644 --- a/src/controllers/endpointcontroller.go +++ b/src/controllers/endpointcontroller.go @@ -34,6 +34,7 @@ type Service struct { TransportInfo TransportInfo `yaml:"transportInfo" json:"transportInfo"` } +// Transport information of the service. type TransportInfo struct { Id string `yaml:"id" json:"id"` Name string `yaml:"name" json:"name"` @@ -43,6 +44,7 @@ type TransportInfo struct { Endpoint EndPointInfo `yaml:"endpoint" json:"endpoint"` } +// End point of the service. type EndPointInfo struct { Uris []string `json:"uris" validate:"omitempty,dive,uri"` Addresses []EndPointInfoAddress `json:"addresses" validate:"omitempty,dive"` @@ -58,12 +60,7 @@ func (c *EndpointController) Get() { log.Info("received get endpoint request from app") serName := c.Ctx.Input.Param(":serName") - server, errGetServer := config.GetServerUrl() - if errGetServer != nil { - log.Error("Failed to get serviceUrl") - } - - url := server.MepServiceDiscoveryUrl + serName + url := config.ServerUrlConfig.MepServiceDiscoveryUrl + serName requestData := service.RequestData{Data: "", Url: url, Token: &util.MepToken} resBody, errPostRequest := service.SendQueryRequest(requestData) diff --git a/src/main/main.go b/src/main/main.go index 8ce7fb8bc609eda224ea02452afd343110032562..0cb0ffd4928157bafc540f387e661d2d1105be7f 100644 --- a/src/main/main.go +++ b/src/main/main.go @@ -19,6 +19,7 @@ package main import ( "github.com/astaxie/beego" log "github.com/sirupsen/logrus" + "mep-agent/src/config" "mep-agent/src/controllers" _ "mep-agent/src/router" "mep-agent/src/service" @@ -35,8 +36,16 @@ func main() { os.Exit(1) } - if err := util.ValidateAkSk(string(*util.AppConfig["ACCESS_KEY"]), util.AppConfig["SECRET_KEY"]); err != nil { - log.Error("the input param of ak or sk do not pass the validation") + service.TlsConf, err = service.TlsConfig() + if err != nil { + log.Error("Failed to set TLS Configurations") + util.ClearMap() + os.Exit(1) + } + + config.ServerUrlConfig, err = config.GetServerUrl() + if err != nil { + log.Error("Failed to get server url Configurations") util.ClearMap() os.Exit(1) } diff --git a/src/model/instance.go b/src/model/instance.go index 0729b5ae68135abf95bdd0e7d6924a7644b3888c..c897ac9f4680e1f861cba33b7a413eea6a7fc980 100644 --- a/src/model/instance.go +++ b/src/model/instance.go @@ -22,6 +22,7 @@ type AppInstanceInfo struct { SerAvailabilityNotificationSubscriptions []SerAvailabilityNotificationSubscription `yaml:"serAvailabilityNotificationSubscriptions" json:"serAvailabilityNotificationSubscriptions"` } +// Service Information to be registered. type ServiceInfoPost struct { SerName string `yaml:"serName" json:"serName"` SerCategory CategoryRef `yaml:"serCategory" json:"serCategory"` @@ -53,6 +54,7 @@ type CategoryRef struct { type ServiceState string +// Transport Information of the service to be registered. type TransportInfo struct { Id string `yaml:"id" json:"id"` Name string `yaml:"name" json:"name"` @@ -67,6 +69,7 @@ type TransportInfo struct { type TransportType string +// Endpoint of the service to be registered. type EndPointInfo struct { Addresses []EndPointInfoAddress `yaml:"addresses" json:"addresses"` } diff --git a/src/service/heart.go b/src/service/heart.go index b949fc901ef193baf5b73868915ad1929ba44734..b5d6fb25178cb46d51506de213414f2f93a1c159 100644 --- a/src/service/heart.go +++ b/src/service/heart.go @@ -22,7 +22,6 @@ import ( log "github.com/sirupsen/logrus" "mep-agent/src/config" "mep-agent/src/model" - "time" "mep-agent/src/util" ) @@ -36,11 +35,6 @@ type ServiceLivenessUpdate struct { State string `json:"state"` } -// Sleeps for an hour -func Heart() { - time.Sleep(time.Hour) -} - // Send service heartbeat to MEP func HeartBeatRequestToMep(serviceInfo model.ServiceInfoPost) { @@ -48,14 +42,10 @@ func HeartBeatRequestToMep(serviceInfo model.ServiceInfoPost) { data, errJsonMarshal := json.Marshal(heartBeatRequest) if errJsonMarshal != nil { log.Error("Failed to marshal service info to object") + return } - server, errGetServer := config.GetServerUrl() - if errGetServer != nil { - log.Error("Failed to get serviceUrl") - } - - url := server.MepHeartBeatUrl + serviceInfo.Links.Self.Liveness + url := config.ServerUrlConfig.MepHeartBeatUrl + serviceInfo.Links.Self.Liveness var heartBeatData = HeartBeatData{data: string(data), url: url, token: &util.MepToken} _, errPostRequest := SendHeartBeatRequest(heartBeatData) if errPostRequest != nil { diff --git a/src/service/register.go b/src/service/register.go index ff2affc0c5c7f46f1aa183e05ead3473ae177591..8f5ef92d0c80106f4cc5da997aee836ac0e4d3af 100644 --- a/src/service/register.go +++ b/src/service/register.go @@ -56,16 +56,12 @@ func RegisterToMep(conf model.AppInstanceInfo, wg *sync.WaitGroup) ([]model.Serv return nil, errors.New("Registration of service failed, cannot contain more than " + strconv.Itoa(MAX_SERVICE_COUNT) + " services in a single request") } - server, errGetServer := config.GetServerUrl() - if errGetServer != nil { - return nil, errGetServer - } if util.ValidateUUID(appInstanceId) != nil { return nil, errors.New("validate appInstanceId failed") } - url := strings.Replace(server.MepServerRegisterUrl, "${appInstanceId}", appInstanceId, 1) + url := strings.Replace(config.ServerUrlConfig.MepServerRegisterUrl, "${appInstanceId}", appInstanceId, 1) for _, serviceInfo := range serviceInfos { data, errJsonMarshal := json.Marshal(serviceInfo) diff --git a/src/service/request.go b/src/service/request.go index 8bf9e85320d588b268da9c361a164ace12b3ff4e..cb9b1db4615d6f8cab7310dc7a1262a58254ca4c 100644 --- a/src/service/request.go +++ b/src/service/request.go @@ -35,6 +35,8 @@ import ( const AUTHORIZATION = "Authorization" +var TlsConf *tls.Config + type RequestData struct { Token *model.TokenModel Data string @@ -148,14 +150,9 @@ func PostTokenRequest(param string, url string, auth model.Auth) (string, error) // do request func DoRequest(req *http.Request) (*http.Response, error) { - config, err := TlsConfig() - if err != nil { - log.Error("Unable to send request") - return nil, err - } tr := &http.Transport{ - TLSClientConfig: config, + TLSClientConfig: TlsConf, } client := &http.Client{Transport: tr} @@ -181,6 +178,7 @@ func TlsConfig() (*tls.Config, error) { if util.ValidateDomainName(domainName) != nil { return nil, errors.New("Domain name validation failed") } + return &tls.Config{ ServerName: domainName, MinVersion: tls.VersionTLS12, diff --git a/src/service/token.go b/src/service/token.go index 2a12d4e219aef5cc79f6df950bd339bfee50e0ce..a5e1c14543331765a1903e9a186da175de3d13f7 100644 --- a/src/service/token.go +++ b/src/service/token.go @@ -29,14 +29,9 @@ import ( // Request token from mep_auth func GetMepToken(auth model.Auth) error { - // get request url - server, errGetServer := config.GetServerUrl() - if errGetServer != nil { - return errGetServer - } // construct http request and send - resp, errPostRequest := PostTokenRequest("", server.MepAuthUrl, auth) + resp, errPostRequest := PostTokenRequest("", config.ServerUrlConfig.MepAuthUrl, auth) if errPostRequest != nil { return errPostRequest } diff --git a/src/util/util.go b/src/util/util.go index 50e95755b6bbf237f2b66579dbcbd364dfcc3fd7..469764fd8862f8830f25ffba2902187d7e1dd89c 100644 --- a/src/util/util.go +++ b/src/util/util.go @@ -75,29 +75,31 @@ func ReadTokenFromEnvironment() error { defer os.Unsetenv(AK) defer os.Unsetenv(SK) - if len(os.Getenv(AK)) == 0 || len(os.Getenv(SK)) == 0 { + ak := os.Getenv(AK) + sk := os.Getenv(SK) + + if len(ak) == 0 || len(sk) == 0 { err := errors.New("ak and sk keys should be set in env variable") log.Error("Keys should not be empty") return err } - ak := []byte(os.Getenv(AK)) - AppConfig["ACCESS_KEY"] = &ak - sk := []byte(os.Getenv(SK)) - AppConfig["SECRET_KEY"] = &sk - log.Infof("Ak: %s", ak) + akByte := []byte(ak) + AppConfig["ACCESS_KEY"] = &akByte + skByte := []byte(sk) + AppConfig["SECRET_KEY"] = &skByte + log.Infof("Ak: %s", akByte) return nil } //Read application instanceId func GetAppInstanceId() (string, error) { defer os.Unsetenv(APPINSTID) - if len(os.Getenv(APPINSTID)) == 0 { + instId := os.Getenv(APPINSTID) + if len(instId) == 0 { err := errors.New("appInstanceId should be set in env variable") log.Error("appInstanceId must be set") return "", err } - instId := os.Getenv(APPINSTID) - AppInstanceId = instId - return AppInstanceId, nil + return instId, nil } diff --git a/src/util/validation.go b/src/util/validation.go index a7853bb376111985dde25fb4ac828cce106ac5c9..a0a104e3853cfcb579eddd84eac45d9b7b99f50c 100644 --- a/src/util/validation.go +++ b/src/util/validation.go @@ -25,10 +25,10 @@ import ( ) const ( - IP_PATTERN string = `^[a-z][a-z-]{0,126}[a-z]$` + //IP_PATTERN string = `^[a-z][a-z-]{0,126}[a-z]$` PORT_PATTERN string = `^([1-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$` - AK_PATTERN string = `^\w{20}$` - SK_PATTERN string = `^\w{64}$` + //AK_PATTERN string = `^\w{20}$` + //SK_PATTERN string = `^\w{64}$` DOMAIN_PATTERN string = `^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$` DNS_PATTERN string = `^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$` maxHostNameLen = 253 @@ -37,15 +37,20 @@ const ( // Validates Ip address func ValidateDns(ip string) error { ipv := net.ParseIP(ip) + if ipv != nil && (ipv.IsMulticast() || ipv.Equal(net.IPv4bcast)) { + return errors.New("invalid dns ip") + } + if ipv != nil { return nil } + return ValidateByPattern(DNS_PATTERN, ip) } // Validates domain name func ValidateDomainName(name string) error { - if len(name) > maxHostNameLen { + if len(name) == 0 || len(name) > maxHostNameLen { return errors.New("validate domain name failed") } return ValidateByPattern(DOMAIN_PATTERN, name) @@ -77,29 +82,3 @@ func ValidateUUID(id string) error { return nil } -// Validates SK -func ValidateSkByPattern(pattern string, param *[]byte) error { - res, errMatch := regexp.Match(pattern, *param) - if errMatch != nil { - return errMatch - } - if !res { - return errors.New("validate failed") - } - return nil -} - -// Validates AK and SK -func ValidateAkSk(ak string, sk *[]byte) error { - _ = ak - _ = sk - /* - err := ValidateByPattern(AK_PATTERN, ak) - if err != nil { - return err - } - err = ValidateSkByPattern(SK_PATTERN, sk) - return err - */ - return nil -}