Loading examples/demo3/src/backend/main.go +17 −26 Original line number Diff line number Diff line Loading @@ -12,7 +12,7 @@ import ( "net/http" "os" "os/signal" "strings" "path/filepath" "syscall" "time" Loading @@ -28,35 +28,26 @@ func init() { func main() { var ( envName string envPath string run bool dir string fileName string run bool = true done chan bool ) // Check command arguments for configuration path for _, arg := range os.Args { if strings.HasPrefix(arg, ".") { envPath = arg } } // Parse filename from path resp := strings.LastIndex(envPath, "/") if resp == -1 { log.Fatal("Error parsing command invalid/missing configuration path") // First element in os.Args is always the program name // Require at least 2 arugments to have a file name argument if len(os.Args) < 2 { log.Fatal("Missing parameter, provide file name!") } // Save parsed filename & remove filename from filepath envName = envPath[resp+1:] envPath = envPath[:resp] run = true // Read configuration file path in command line arugments configPath := os.Args[1] dir = filepath.Dir(configPath) fileName = filepath.Base(configPath) go func() { // Configure demo 3 & initialize port, err := server.Init(envPath, envName) port, err := server.Init(dir, fileName) if err != nil { log.Fatal("Failed to initalize Demo 3 ", err) } Loading @@ -70,9 +61,9 @@ func main() { header := handlers.AllowedHeaders([]string{"content-type"}) log.Fatal(http.ListenAndServe(port, handlers.CORS(methods, header)(router))) run = false }() // Listen for SIGKILL go func() { sigchan := make(chan os.Signal, 10) signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM) Loading @@ -81,9 +72,8 @@ func main() { run = false }() // Listen for demo 3 error exit program go func() { // Listen for demo 3 done channel // TODO: what happens when app is shut down & pod behaviour <-done run = false }() Loading @@ -91,6 +81,7 @@ func main() { for { // Invoke graceful termination upon program kill if !run { log.Info("Invoking demo 3 graceful termination") server.Terminate() break } Loading examples/demo3/src/backend/server/demo3_service.go +45 −23 Original line number Diff line number Diff line Loading @@ -108,7 +108,8 @@ var usingDevices []string // List of devices using this ins var terminalDevices map[string]string // Devices registered in ams var terminalDeviceState = make(map[string]int) // Devices registered in ams and their state // Initalize ticker using interval of 1 second to poll mec services and increment terminal device state using this instance by 1 // Initiaze ticker to poll mec services and increment terminal device state every second // It modifies discovered services & state of terminal device using this instance // Stop ticker if deregister app func startTicker() { intervalTicker = time.NewTicker(1 * time.Second) Loading Loading @@ -154,36 +155,59 @@ func startTicker() { demoAppInfo.DiscoveredServices = append(demoAppInfo.DiscoveredServices, tempService) // Store into map with service name key and url value // Store into map by service name key and url value mecServicesMap[tempService.SerName] = tempService.Link } } }() } // Init - Demo Service initalization using config & client packages // Initialize app info from config & apply client package func Init(envPath string, envName string) (port string, err error) { // Initalize config // Initialize config var config util.Config log.Info("Using config values from ", envPath, "/", envName) config, err := util.LoadConfig(envPath, envName) config, err = util.LoadConfig(envPath, envName) if err != nil { log.Fatal("Failed finding config ", err) log.Fatal("Fail to load configuration file ", err) } // Set configuration variables from app_instance yaml // check if app is running externally or on advantedge if config.Mode == "sandbox" { environment = "sandbox" mecUrl = config.SandboxUrl if !strings.HasPrefix(mecUrl, "http://") { mecUrl = "http://" + mecUrl } if !strings.HasSuffix(mecUrl, "/") { mecUrl = strings.TrimSuffix(mecUrl, "/") } localPort = config.Port localUrl = config.Localurl } else if config.Mode == "advantedge" { environment = "advantedge" localPort = ":80" localUrl = "http://" + config.Localurl localUrl = config.Localurl } else { log.Fatal("Check your config mode should be set to advantedge or sandbox") log.Fatal("Config field mode should be set to advantedge or sandbox") } if !strings.HasPrefix(localPort, ":") { localPort = ":" + localPort } if !strings.HasPrefix(localUrl, "http://") { localUrl = "http://" + localUrl } if !strings.HasSuffix(localUrl, "/") { localUrl = strings.TrimSuffix(localUrl, "/") } // Load mec platform name & host url Loading @@ -210,7 +234,7 @@ func Init(envPath string, envName string) (port string, err error) { // Setup application support client & service management client // If running on advantedge prepend mecplatform name to static endpoint // If running on sandbox prepend mec sandbox url to a static endpoint // If running on sandbox set callback url by prepend mec sandbox url to a static endpoint appSupportClientCfg := asc.NewConfiguration() srvMgmtClientCfg := smc.NewConfiguration() if environment == "advantedge" { Loading Loading @@ -247,7 +271,8 @@ func Init(envPath string, envName string) (port string, err error) { return localPort, nil } // If app running on advantedge create mec resource return application info // Create a mec resource on platform // return app id func getAppInstanceId() (id string, err error) { var appInfo sbx.ApplicationInfo appInfo.Name = serviceCategory Loading Loading @@ -504,7 +529,7 @@ func serviceAmsUpdateDevicePut(w http.ResponseWriter, r *http.Request) { _, amsUpdateError := amsAddDevice(amsResourceId, amsResource, device) if amsUpdateError != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Could not update ams") fmt.Fprintf(w, "Could not add ams device") return } Loading @@ -529,7 +554,7 @@ func serviceAmsUpdateDevicePut(w http.ResponseWriter, r *http.Request) { _, updateAmsError := updateAmsSubscription(demoAppInfo.Subscriptions.AmsLinkListSubscription.SubId, device, amsSubscription) if updateAmsError != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Could not update ams subscription") fmt.Fprintf(w, "Could not add ams subscription") return } Loading Loading @@ -617,7 +642,7 @@ func serviceAmsDeleteDeviceDelete(w http.ResponseWriter, r *http.Request) { // Update AMS subscription _, amsSubscriptionErr := updateAmsSubscription(tempId, "", amsSubscriptionResp) if amsSubscriptionErr != nil { log.Error("Failed to update ams subscription", err) log.Error("Failed to delete ams subscription", err) } w.WriteHeader(http.StatusOK) Loading Loading @@ -848,8 +873,6 @@ func amsSendService(appInstanceId string, device string) (string, error) { if err != nil { log.Error(err) log.Info("damn iot i") return "", err } Loading @@ -871,12 +894,11 @@ func amsAddDevice(amsId string, registerationBody ams.RegistrationInfo, device s registerationBody.DeviceInformation = append(registerationBody.DeviceInformation, ams.RegistrationInfoDeviceInformation{ AssociateId: &associateId, AppMobilityServiceLevel: 3, ContextTransferState: 0, }) registerationInfo, _, err := amsClient.AmsiApi.AppMobilityServiceByIdPUT(context.TODO(), registerationBody, amsId) registerationInfo, resp, err := amsClient.AmsiApi.AppMobilityServiceByIdPUT(context.TODO(), registerationBody, amsId) if err != nil { log.Error(err) log.Error("resp status", resp, err) return registerationBody, err } Loading Loading @@ -980,7 +1002,7 @@ func sendReadyConfirmation(appInstanceId string) error { // Client request to retrieve list of mec service resources on sandbox func getMecServices() ([]smc.ServiceInfo, error) { log.Debug("Sending request to mec platform get service resources api ") // log.Debug("Sending request to mec platform get service resources api ") appServicesResponse, resp, err := srvMgmtClient.MecServiceMgmtApi.ServicesGET(context.TODO(), nil) if err != nil { log.Error("Failed to fetch services on mec platform ", resp.Status) Loading @@ -1001,7 +1023,7 @@ func getMecServices() ([]smc.ServiceInfo, error) { // Client request to create a mec-service resource func registerService(appInstanceId string, callBackUrl string) (smc.ServiceInfo, error) { log.Debug("Sending request to mec platform post service resource api ") //log.Debug("Sending request to mec platform post service resource api ") var srvInfo smc.ServiceInfoPost //serName srvInfo.SerName = serviceCategory Loading Loading @@ -1048,8 +1070,8 @@ func registerService(appInstanceId string, callBackUrl string) (smc.ServiceInfo, log.Error("Failed to register service resource on mec app enablement registry: ", resp.Status) return appServicesPostResponse, err } log.Info("LOCALURL: " + localUrl + localPort) log.Info(serviceCategory, " service resource created with instance id: ", appServicesPostResponse.SerInstanceId) // log.Info("LOCALURL: " + localUrl + localPort) // log.Info(serviceCategory, " service resource created with instance id: ", appServicesPostResponse.SerInstanceId) appEnablementServiceId = appServicesPostResponse.SerInstanceId return appServicesPostResponse, nil } Loading examples/demo3/src/backend/util/config.go +5 −8 Original line number Diff line number Diff line Loading @@ -4,8 +4,6 @@ import ( "github.com/spf13/viper" ) // Config stores all configuration of Demo 3 // The values are read by viper from a config file or env file type Config struct { Mode string `mapstructure: mode` SandboxUrl string `mapstructure:"sandbox"` Loading @@ -14,24 +12,23 @@ type Config struct { AppInstanceId string `mapstructure:"appid"` Localurl string `mapstructure:"localurl"` Port string `mapstructure:"port"` //SbxController string `mapstructure:sandboxcontrollerurl` // EnablementUrl string `mapstructure:meepenablementurl` // MecIp string `mapstructure:mecip` } // LoadConfig reads configuration from a environment variable specified by path func LoadConfig(path string, name string) (config Config, err error) { viper.SetConfigType("yaml") viper.AddConfigPath(path) viper.SetConfigName(name) viper.AutomaticEnv() err = viper.ReadInConfig() if err != nil { return return config, err } err = viper.Unmarshal(&config) if err != nil { return config, err } return } examples/demo3/src/frontend/src/js/containers/Homepage.js +7 −5 Original line number Diff line number Diff line Loading @@ -44,7 +44,7 @@ export default function Homepage() { var basepath; if (process.env.ENVIRONMENT === 'SANDBOX') { basepath = process.env.URL; basepath = 'http://' + process.env.URL; } else { basepath = 'http://' + location.host + location.pathname; } Loading Loading @@ -124,7 +124,6 @@ export default function Homepage() { console.log(error); } else { setAppLog(response.body); console.log(response.body); } }); }, 1000); Loading Loading @@ -164,12 +163,14 @@ export default function Homepage() { const removeAmsDevice = async (device) => { let mutableArray = terminalDevices; const result = mutableArray.filter(e => e != device ); appInfoApi.serviceAmsDeleteDeviceDelete(device, (err, data, resp) => { if (err != null) { console.log(err); } } else { const result = mutableArray.filter(e => e != device ); setTerminalDevices(result); } }); }; Loading @@ -180,8 +181,9 @@ export default function Homepage() { appInfoApi.serviceAmsUpdateDevicePut(textValue, (err, data, resp) => { if (err != null) { console.log(err); } } else { setTerminalDevices(e => [... e, textValue]); } }); } }; Loading Loading
examples/demo3/src/backend/main.go +17 −26 Original line number Diff line number Diff line Loading @@ -12,7 +12,7 @@ import ( "net/http" "os" "os/signal" "strings" "path/filepath" "syscall" "time" Loading @@ -28,35 +28,26 @@ func init() { func main() { var ( envName string envPath string run bool dir string fileName string run bool = true done chan bool ) // Check command arguments for configuration path for _, arg := range os.Args { if strings.HasPrefix(arg, ".") { envPath = arg } } // Parse filename from path resp := strings.LastIndex(envPath, "/") if resp == -1 { log.Fatal("Error parsing command invalid/missing configuration path") // First element in os.Args is always the program name // Require at least 2 arugments to have a file name argument if len(os.Args) < 2 { log.Fatal("Missing parameter, provide file name!") } // Save parsed filename & remove filename from filepath envName = envPath[resp+1:] envPath = envPath[:resp] run = true // Read configuration file path in command line arugments configPath := os.Args[1] dir = filepath.Dir(configPath) fileName = filepath.Base(configPath) go func() { // Configure demo 3 & initialize port, err := server.Init(envPath, envName) port, err := server.Init(dir, fileName) if err != nil { log.Fatal("Failed to initalize Demo 3 ", err) } Loading @@ -70,9 +61,9 @@ func main() { header := handlers.AllowedHeaders([]string{"content-type"}) log.Fatal(http.ListenAndServe(port, handlers.CORS(methods, header)(router))) run = false }() // Listen for SIGKILL go func() { sigchan := make(chan os.Signal, 10) signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM) Loading @@ -81,9 +72,8 @@ func main() { run = false }() // Listen for demo 3 error exit program go func() { // Listen for demo 3 done channel // TODO: what happens when app is shut down & pod behaviour <-done run = false }() Loading @@ -91,6 +81,7 @@ func main() { for { // Invoke graceful termination upon program kill if !run { log.Info("Invoking demo 3 graceful termination") server.Terminate() break } Loading
examples/demo3/src/backend/server/demo3_service.go +45 −23 Original line number Diff line number Diff line Loading @@ -108,7 +108,8 @@ var usingDevices []string // List of devices using this ins var terminalDevices map[string]string // Devices registered in ams var terminalDeviceState = make(map[string]int) // Devices registered in ams and their state // Initalize ticker using interval of 1 second to poll mec services and increment terminal device state using this instance by 1 // Initiaze ticker to poll mec services and increment terminal device state every second // It modifies discovered services & state of terminal device using this instance // Stop ticker if deregister app func startTicker() { intervalTicker = time.NewTicker(1 * time.Second) Loading Loading @@ -154,36 +155,59 @@ func startTicker() { demoAppInfo.DiscoveredServices = append(demoAppInfo.DiscoveredServices, tempService) // Store into map with service name key and url value // Store into map by service name key and url value mecServicesMap[tempService.SerName] = tempService.Link } } }() } // Init - Demo Service initalization using config & client packages // Initialize app info from config & apply client package func Init(envPath string, envName string) (port string, err error) { // Initalize config // Initialize config var config util.Config log.Info("Using config values from ", envPath, "/", envName) config, err := util.LoadConfig(envPath, envName) config, err = util.LoadConfig(envPath, envName) if err != nil { log.Fatal("Failed finding config ", err) log.Fatal("Fail to load configuration file ", err) } // Set configuration variables from app_instance yaml // check if app is running externally or on advantedge if config.Mode == "sandbox" { environment = "sandbox" mecUrl = config.SandboxUrl if !strings.HasPrefix(mecUrl, "http://") { mecUrl = "http://" + mecUrl } if !strings.HasSuffix(mecUrl, "/") { mecUrl = strings.TrimSuffix(mecUrl, "/") } localPort = config.Port localUrl = config.Localurl } else if config.Mode == "advantedge" { environment = "advantedge" localPort = ":80" localUrl = "http://" + config.Localurl localUrl = config.Localurl } else { log.Fatal("Check your config mode should be set to advantedge or sandbox") log.Fatal("Config field mode should be set to advantedge or sandbox") } if !strings.HasPrefix(localPort, ":") { localPort = ":" + localPort } if !strings.HasPrefix(localUrl, "http://") { localUrl = "http://" + localUrl } if !strings.HasSuffix(localUrl, "/") { localUrl = strings.TrimSuffix(localUrl, "/") } // Load mec platform name & host url Loading @@ -210,7 +234,7 @@ func Init(envPath string, envName string) (port string, err error) { // Setup application support client & service management client // If running on advantedge prepend mecplatform name to static endpoint // If running on sandbox prepend mec sandbox url to a static endpoint // If running on sandbox set callback url by prepend mec sandbox url to a static endpoint appSupportClientCfg := asc.NewConfiguration() srvMgmtClientCfg := smc.NewConfiguration() if environment == "advantedge" { Loading Loading @@ -247,7 +271,8 @@ func Init(envPath string, envName string) (port string, err error) { return localPort, nil } // If app running on advantedge create mec resource return application info // Create a mec resource on platform // return app id func getAppInstanceId() (id string, err error) { var appInfo sbx.ApplicationInfo appInfo.Name = serviceCategory Loading Loading @@ -504,7 +529,7 @@ func serviceAmsUpdateDevicePut(w http.ResponseWriter, r *http.Request) { _, amsUpdateError := amsAddDevice(amsResourceId, amsResource, device) if amsUpdateError != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Could not update ams") fmt.Fprintf(w, "Could not add ams device") return } Loading @@ -529,7 +554,7 @@ func serviceAmsUpdateDevicePut(w http.ResponseWriter, r *http.Request) { _, updateAmsError := updateAmsSubscription(demoAppInfo.Subscriptions.AmsLinkListSubscription.SubId, device, amsSubscription) if updateAmsError != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Could not update ams subscription") fmt.Fprintf(w, "Could not add ams subscription") return } Loading Loading @@ -617,7 +642,7 @@ func serviceAmsDeleteDeviceDelete(w http.ResponseWriter, r *http.Request) { // Update AMS subscription _, amsSubscriptionErr := updateAmsSubscription(tempId, "", amsSubscriptionResp) if amsSubscriptionErr != nil { log.Error("Failed to update ams subscription", err) log.Error("Failed to delete ams subscription", err) } w.WriteHeader(http.StatusOK) Loading Loading @@ -848,8 +873,6 @@ func amsSendService(appInstanceId string, device string) (string, error) { if err != nil { log.Error(err) log.Info("damn iot i") return "", err } Loading @@ -871,12 +894,11 @@ func amsAddDevice(amsId string, registerationBody ams.RegistrationInfo, device s registerationBody.DeviceInformation = append(registerationBody.DeviceInformation, ams.RegistrationInfoDeviceInformation{ AssociateId: &associateId, AppMobilityServiceLevel: 3, ContextTransferState: 0, }) registerationInfo, _, err := amsClient.AmsiApi.AppMobilityServiceByIdPUT(context.TODO(), registerationBody, amsId) registerationInfo, resp, err := amsClient.AmsiApi.AppMobilityServiceByIdPUT(context.TODO(), registerationBody, amsId) if err != nil { log.Error(err) log.Error("resp status", resp, err) return registerationBody, err } Loading Loading @@ -980,7 +1002,7 @@ func sendReadyConfirmation(appInstanceId string) error { // Client request to retrieve list of mec service resources on sandbox func getMecServices() ([]smc.ServiceInfo, error) { log.Debug("Sending request to mec platform get service resources api ") // log.Debug("Sending request to mec platform get service resources api ") appServicesResponse, resp, err := srvMgmtClient.MecServiceMgmtApi.ServicesGET(context.TODO(), nil) if err != nil { log.Error("Failed to fetch services on mec platform ", resp.Status) Loading @@ -1001,7 +1023,7 @@ func getMecServices() ([]smc.ServiceInfo, error) { // Client request to create a mec-service resource func registerService(appInstanceId string, callBackUrl string) (smc.ServiceInfo, error) { log.Debug("Sending request to mec platform post service resource api ") //log.Debug("Sending request to mec platform post service resource api ") var srvInfo smc.ServiceInfoPost //serName srvInfo.SerName = serviceCategory Loading Loading @@ -1048,8 +1070,8 @@ func registerService(appInstanceId string, callBackUrl string) (smc.ServiceInfo, log.Error("Failed to register service resource on mec app enablement registry: ", resp.Status) return appServicesPostResponse, err } log.Info("LOCALURL: " + localUrl + localPort) log.Info(serviceCategory, " service resource created with instance id: ", appServicesPostResponse.SerInstanceId) // log.Info("LOCALURL: " + localUrl + localPort) // log.Info(serviceCategory, " service resource created with instance id: ", appServicesPostResponse.SerInstanceId) appEnablementServiceId = appServicesPostResponse.SerInstanceId return appServicesPostResponse, nil } Loading
examples/demo3/src/backend/util/config.go +5 −8 Original line number Diff line number Diff line Loading @@ -4,8 +4,6 @@ import ( "github.com/spf13/viper" ) // Config stores all configuration of Demo 3 // The values are read by viper from a config file or env file type Config struct { Mode string `mapstructure: mode` SandboxUrl string `mapstructure:"sandbox"` Loading @@ -14,24 +12,23 @@ type Config struct { AppInstanceId string `mapstructure:"appid"` Localurl string `mapstructure:"localurl"` Port string `mapstructure:"port"` //SbxController string `mapstructure:sandboxcontrollerurl` // EnablementUrl string `mapstructure:meepenablementurl` // MecIp string `mapstructure:mecip` } // LoadConfig reads configuration from a environment variable specified by path func LoadConfig(path string, name string) (config Config, err error) { viper.SetConfigType("yaml") viper.AddConfigPath(path) viper.SetConfigName(name) viper.AutomaticEnv() err = viper.ReadInConfig() if err != nil { return return config, err } err = viper.Unmarshal(&config) if err != nil { return config, err } return }
examples/demo3/src/frontend/src/js/containers/Homepage.js +7 −5 Original line number Diff line number Diff line Loading @@ -44,7 +44,7 @@ export default function Homepage() { var basepath; if (process.env.ENVIRONMENT === 'SANDBOX') { basepath = process.env.URL; basepath = 'http://' + process.env.URL; } else { basepath = 'http://' + location.host + location.pathname; } Loading Loading @@ -124,7 +124,6 @@ export default function Homepage() { console.log(error); } else { setAppLog(response.body); console.log(response.body); } }); }, 1000); Loading Loading @@ -164,12 +163,14 @@ export default function Homepage() { const removeAmsDevice = async (device) => { let mutableArray = terminalDevices; const result = mutableArray.filter(e => e != device ); appInfoApi.serviceAmsDeleteDeviceDelete(device, (err, data, resp) => { if (err != null) { console.log(err); } } else { const result = mutableArray.filter(e => e != device ); setTerminalDevices(result); } }); }; Loading @@ -180,8 +181,9 @@ export default function Homepage() { appInfoApi.serviceAmsUpdateDevicePut(textValue, (err, data, resp) => { if (err != null) { console.log(err); } } else { setTerminalDevices(e => [... e, textValue]); } }); } }; Loading