From 03b614b93b2eb3e3870e37fe138c7a3803175dc0 Mon Sep 17 00:00:00 2001 From: Samiul Hoque Date: Sun, 24 Feb 2019 14:00:21 +0600 Subject: [PATCH] Add configuration management and physical activity changes --- Makefile | 13 +- cmd/ohal/main.go | 12 +- .../goals_hearts.json | 0 .../goals_hearts_content.json | 0 .../guideline_hearts.json | 0 .../guideline_hearts_content.json | 0 documentation/README.md | 39 +++- ohas.toml | 14 ++ pkg/algorithms/hearts/hearts.go | 2 +- pkg/config/config.go | 112 ++++------ pkg/config/types.go | 211 +----------------- pkg/config/variables.go | 105 --------- pkg/config/variables_posix.go | 80 ------- pkg/config/variables_windows.go | 91 -------- pkg/engine/lifestyle.go | 40 +++- pkg/service/service.go | 17 +- pkg/version.go | 2 +- 17 files changed, 159 insertions(+), 579 deletions(-) rename goals_hearts.json => contents/goals_hearts.json (100%) rename goals_hearts_content.json => contents/goals_hearts_content.json (100%) rename guideline_hearts.json => contents/guideline_hearts.json (100%) rename guideline_hearts_content.json => contents/guideline_hearts_content.json (100%) create mode 100644 ohas.toml delete mode 100644 pkg/config/variables.go delete mode 100644 pkg/config/variables_posix.go delete mode 100644 pkg/config/variables_windows.go diff --git a/Makefile b/Makefile index 5bd02ce..1b3f7f3 100644 --- a/Makefile +++ b/Makefile @@ -36,12 +36,14 @@ ART_ALG_LINUX_32 := $(DEV_ALG_NAME)-linux-386.bin ART_ALG_LINUX_64 := $(DEV_ALG_NAME)-linux-amd64.bin # default files to include -GUIDELINE_JSON := guideline_hearts.json -GUIDELINE_CONTENT_JSON := guideline_hearts_content.json -GOALS_JSON := goals_hearts.json -GOALS_CONTENT_JSON := goals_hearts_content.json +# GUIDELINE_JSON := guideline_hearts.json +# GUIDELINE_CONTENT_JSON := guideline_hearts_content.json +# GOALS_JSON := goals_hearts.json +# GOALS_CONTENT_JSON := goals_hearts_content.json SAMPLE_REQUEST_JSON := sample-request.json HELP_FILE := ./documentation +CONTENTS_FILE := ./contents +CONFIG_FILE := ohas.toml # tests COVER_OUT := cover.out @@ -122,7 +124,8 @@ artifacts_linux: ## Create artifacts for linux zip_artifacts: ## Create a zip archive with artifacts $(MAKE) -f $(MKFILE_PATH) clean_releases mkdir -p $(REL_PATH) - zip -j -v $(REL_PATH)/$(ART_ARCHIVE) $(BUILD_DARWIN)/$(ART_DARWIN_64) $(BUILD_LINUX)/$(ART_LINUX_64) $(GUIDELINE_JSON) $(GUIDELINE_CONTENT_JSON) $(GOALS_JSON) $(GOALS_CONTENT_JSON) $(SAMPLE_REQUEST_JSON) + zip -j -v $(REL_PATH)/$(ART_ARCHIVE) $(BUILD_DARWIN)/$(ART_DARWIN_64) $(BUILD_LINUX)/$(ART_LINUX_64) $(CONFIG_FILE) $(SAMPLE_REQUEST_JSON) + zip -v -r -u $(REL_PATH)/$(ART_ARCHIVE) $(CONTENTS_FILE) zip -v -r -u $(REL_PATH)/$(ART_ARCHIVE) $(HELP_FILE) house_keep: ## Remove any .DS_Store files diff --git a/cmd/ohal/main.go b/cmd/ohal/main.go index 080ed09..6d91370 100644 --- a/cmd/ohal/main.go +++ b/cmd/ohal/main.go @@ -12,6 +12,8 @@ import ( "runtime/pprof" "sort" + "github.com/openhealthalgorithms/service/pkg/config" + "github.com/openhealthalgorithms/service/pkg" "github.com/openhealthalgorithms/service/pkg/algorithms" heartsAlg "github.com/openhealthalgorithms/service/pkg/algorithms/hearts" @@ -163,6 +165,8 @@ func setupAndRun(cliCtx *cli.Context) error { flag.BoolVar(&debug, "debug", false, "debug flag") flag.Parse() + currentSettings := config.CurrentSettings() + if cpuProf { f, err := os.Create(cpuprofile) if err != nil { @@ -251,10 +255,10 @@ func setupAndRun(cliCtx *cli.Context) error { v := types.NewValuesCtx() v.Params.Set("params", paramObj) - v.Params.Set("guide", guideline) - v.Params.Set("guidecontent", guidelineContent) - v.Params.Set("goal", goal) - v.Params.Set("goalcontent", goalContent) + v.Params.Set("guide", currentSettings.GuidelineFile) + v.Params.Set("guidecontent", currentSettings.GuidelineContentFile) + v.Params.Set("goal", currentSettings.GoalFile) + v.Params.Set("goalcontent", currentSettings.GoalContentFile) if debug { v.Params.Set("debug", "true") diff --git a/goals_hearts.json b/contents/goals_hearts.json similarity index 100% rename from goals_hearts.json rename to contents/goals_hearts.json diff --git a/goals_hearts_content.json b/contents/goals_hearts_content.json similarity index 100% rename from goals_hearts_content.json rename to contents/goals_hearts_content.json diff --git a/guideline_hearts.json b/contents/guideline_hearts.json similarity index 100% rename from guideline_hearts.json rename to contents/guideline_hearts.json diff --git a/guideline_hearts_content.json b/contents/guideline_hearts_content.json similarity index 100% rename from guideline_hearts_content.json rename to contents/guideline_hearts_content.json diff --git a/documentation/README.md b/documentation/README.md index 29b977f..9c52b49 100644 --- a/documentation/README.md +++ b/documentation/README.md @@ -22,12 +22,14 @@ in a zip file, unzip to a directory of your choice. This zip file contains the f |-- icon.png |-- index.html |-- README.md (This file) - |-- goals_hearts_content.json (Has the goals content for various health check) - |-- goals_hearts.json (Has the goals conditions for various health check) - |-- guideline_hearts_content.json (Has the care plan messages for different attributes) - |-- guideline_hearts.json (Has the conditions/targets for various health check) + |-- contents + |-- goals_hearts_content.json (Has the goals content for various health check) + |-- goals_hearts.json (Has the goals conditions for various health check) + |-- guideline_hearts_content.json (Has the care plan messages for different attributes) + |-- guideline_hearts.json (Has the conditions/targets for various health check) |-- ohas-darwin-amd64.bin (The binary you can use in Mac) |-- ohas-linux-amd64.bin (The binary you can use in Linux) + |-- ohas.toml |-- sample-request.json (A sample request object) ``` @@ -43,6 +45,35 @@ To stop Service, run the following command: cd ~/ohas && ./ohas-linux-amd64.bin stop ``` +You'll need to modify the `ohas.toml` config file for your system. By default, the system will check for this config file in the following directories (from high to low priority): + +```text +/etc/ohas/ +/usr/local/ohas/ +/usr/local/etc/ohas/ +/var/lib/ohas/ +Current Directory +``` + +A sample structure of the config file: + +```toml +[server] +port = "9595" # define port number to run the service. It's your responsibility to select an unused port number. + +[files] +guideline_file = "guideline_hearts.json" # name of the guideline JSON file +guideline_content_file = "guideline_hearts_content.json" # name of the guideline content JSON file +goal_file = "goals_hearts.json" # name of the goal JSON file +goal_content_file = "goals_hearts_content.json" # name of the goal content JSON file +log_file = "ohas-logs.db" # name of the logs database file + +[directories] +guideline_path = "contents" # path of the directory for guideline JSON and guideline content JSON file +goal_path = "contents" # path of the directory for goal JSON and goal content JSON file +log_file_path = "~" # path of the log file +``` + To view the documentation in the given html file, run it within a webserver. For example, you can run a simple server for preview: diff --git a/ohas.toml b/ohas.toml new file mode 100644 index 0000000..37fcdaf --- /dev/null +++ b/ohas.toml @@ -0,0 +1,14 @@ +[server] +port = "9595" # define port number to run the service. It's your responsibility to select an unused port number. + +[files] +guideline_file = "guideline_hearts.json" # name of the guideline JSON file +guideline_content_file = "guideline_hearts_content.json" # name of the guideline content JSON file +goal_file = "goals_hearts.json" # name of the goal JSON file +goal_content_file = "goals_hearts_content.json" # name of the goal content JSON file +log_file = "ohas-logs.db" # name of the logs database file + +[directories] +guideline_path = "contents" # path of the directory for guideline JSON and guideline content JSON file +goal_path = "contents" # path of the directory for goal JSON and goal content JSON file +log_file_path = "~" # path of the log file diff --git a/pkg/algorithms/hearts/hearts.go b/pkg/algorithms/hearts/hearts.go index 869ff51..61e7abf 100644 --- a/pkg/algorithms/hearts/hearts.go +++ b/pkg/algorithms/hearts/hearts.go @@ -205,7 +205,7 @@ func (d *Data) get(ctx context.Context) error { } // Physical Activity - ph, err := engineGuide.Body.Lifestyle.PhysicalActivity.Process(p.PhysicalActivity) + ph, err := engineGuide.Body.Lifestyle.PhysicalActivity.Process(p.PhysicalActivity, p.Gender, p.Age) if err != nil { errs = append(errs, err.Error()) } else { diff --git a/pkg/config/config.go b/pkg/config/config.go index f5afdad..359bf92 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -1,88 +1,58 @@ -// Package config provides configuration constants and variables for the agent. -// -// WARNING: This package must not import any other agent's package. -// Otherwide the circle dependency might occur. +// Package config provides configuration constants and variables package config import ( - "time" -) - -// Default contains default configuration settings. -var Default Settings = NewSettings() + "path/filepath" -// NewSettings returns default configuration settings. -// -// WARNING! All the configuration MUST be done by setting appropriate values here! -func NewSettings() Settings { - agent := &Agent{ - // The number of tasks being executing simultaneously. - maxTaskExecutors: 4, - // An URL which is used when --local flag is passed. - // Must not be changed. - localServerURL: "http://127.0.0.1:8080", + "github.com/spf13/viper" +) - // Interval between iterations. - loopInterval: 60 * time.Second, - startDelayDuration: 2 * time.Minute, +// CurrentSettings function selects and responds correct settings +func CurrentSettings() Settings { + v := viper.New() + defaults := defaultSettings() - // Default Timeout for shell commands. - // Must not be changed. - cmdexecTimeout: 10 * time.Second, + for key, value := range defaults { + v.SetDefault(key, value) } - api := &API{ - Methods: map[string]string{ - EPCompanyConfiguration: "/api/v2.1/company-configuration", - EPConnections: "/api/v2.1/connections", - EPFile: "/api/v2/file", - EPFileSearch: "/api/v2/file-search", - EPFileSystem: "/api/v2/filesystem-snapshot", - EPLog: "/api/v2/log", - EPRegister: "/api/v2/agent/register", - EPReport: "/api/v2/report", - }, - } + v.SetConfigName("ohas") + v.AddConfigPath("/etc/ohas/") + v.AddConfigPath("/usr/local/ohas/") + v.AddConfigPath("/usr/local/etc/ohas/") + v.AddConfigPath("/var/lib/ohas/") + v.AddConfigPath(".") - common := &Common{ - appAuthorName: "CF Automation", - appAuthorEmail: "ms.cf.automation@aurea.com", - licenseKey: "unknown", - serverURL: "https://gravity.devfactory.com", - logDestination: "combined", - logLevel: "info", - logMaxFileSize: 10 * 1 << 20, + v.ReadInConfig() - // Daemon graceful timeout. - gracefulTimeout: 15 * time.Second, - connMapDuration: 10 * 60 * 60, - } + return configSettings(v) +} - http := &HTTP{ - // This value sets actual timeout for http client. - clientTimeout: 180 * time.Second, +func defaultSettings() map[string]interface{} { + settings := map[string]interface{}{ + "server.port": "9595", + "files.guideline_file": "guideline_hearts.json", + "files.guideline_content_file": "guideline_hearts_content.json", + "files.goal_file": "goals_hearts.json", + "files.goal_content_file": "goals_hearts_content.json", + "files.log_file": "logs.db", + "directories.guideline_path": "", + "directories.goal_path": "", + "directories.log_file_path": "", + } - // Settings for retry in httplib.Service. - backoffMinTimeout: 100 * time.Millisecond, - backoffMaxTimeout: 5 * time.Minute, - backoffFactor: 2, + return settings +} - // Low level http transport settings. - // They must not be changed at all. - dialTimeout: 30 * time.Second, - keepAlive: 30 * time.Second, - tLSHandshakeTimeout: 10 * time.Second, - idleConnTimeout: 90 * time.Second, - expectContinueTimeout: 1 * time.Second, - } +func configSettings(v *viper.Viper) Settings { + settings := Settings{} - settings := Settings{ - Agent: agent, - API: api, - Common: common, - HTTP: http, - Operations: operationsList, - } + settings.Port = v.GetString("server.port") + settings.GuidelineFile = filepath.Join(v.GetString("directories.guideline_path"), v.GetString("files.guideline_file")) + settings.GuidelineContentFile = filepath.Join(v.GetString("directories.guideline_path"), v.GetString("files.guideline_content_file")) + settings.GoalFile = filepath.Join(v.GetString("directories.goal_path"), v.GetString("files.goal_file")) + settings.GoalContentFile = filepath.Join(v.GetString("directories.goal_path"), v.GetString("files.goal_content_file")) + settings.LogFile = filepath.Join(v.GetString("directories.log_file_path"), v.GetString("files.log_file")) return settings } diff --git a/pkg/config/types.go b/pkg/config/types.go index 01d65c8..7bca1d0 100644 --- a/pkg/config/types.go +++ b/pkg/config/types.go @@ -1,210 +1,11 @@ package config -import ( - "time" -) - // Settings represents settings for the application. type Settings struct { - Agent *Agent - API *API - Common *Common - HTTP *HTTP - Operations []Operation -} - -// Agent holds settings for agent. -type Agent struct { - localServerURL string - maxTaskExecutors int - loopInterval time.Duration - startDelayDuration time.Duration - cmdexecTimeout time.Duration -} - -// MaxTaskExecutors returns the corresponding private value. -func (c *Agent) MaxTaskExecutors() int { - return c.maxTaskExecutors -} - -// LocalServerURL returns the corresponding private value. -func (c *Agent) LocalServerURL() string { - return c.localServerURL -} - -// LoopInterval returns the corresponding private value. -func (c *Agent) LoopInterval() time.Duration { - return c.loopInterval -} - -// StartDelayDuration returns the corresponding private value. -func (c *Agent) StartDelayDuration() time.Duration { - return c.startDelayDuration -} - -// CmdexecTimeout returns the corresponding private value. -func (c *Agent) CmdexecTimeout() time.Duration { - return c.cmdexecTimeout -} - -// API holds settings related to Gravity Backend. -type API struct { - Methods map[string]string -} - -// Common holds settings for various things. -type Common struct { - appAuthorName string - appAuthorEmail string - serverURL string - licenseKey string - logLevel string - logDestination string - gracefulTimeout time.Duration - logMaxFileSize int64 - connMapDuration int -} - -// AppAuthorName returns the corresponding private value. -func (c *Common) AppAuthorName() string { - return c.appAuthorName -} - -// AppAuthorEmail returns the corresponding private value. -func (c *Common) AppAuthorEmail() string { - return c.appAuthorEmail -} - -// ServerURL returns the corresponding private value. -func (c *Common) ServerURL() string { - return c.serverURL -} - -// LicenseKey returns the corresponding private value. -func (c *Common) LicenseKey() string { - return c.licenseKey -} - -// LogLevel returns the corresponding private value. -func (c *Common) LogLevel() string { - return c.logLevel -} - -// LogDestination returns the corresponding private value. -func (c *Common) LogDestination() string { - return c.logDestination -} - -// GracefulTimeout returns the corresponding private value. -func (c *Common) GracefulTimeout() time.Duration { - return c.gracefulTimeout -} - -// LogMaxFileSize returns the corresponding private value. -func (c *Common) LogMaxFileSize() int64 { - return c.logMaxFileSize -} - -// ConnMapDuration returns the corresponding private value. -func (c *Common) ConnMapDuration() int { - return c.connMapDuration -} - -// HTTP holds settings for http layer. -type HTTP struct { - clientTimeout time.Duration - dialTimeout time.Duration - keepAlive time.Duration - tLSHandshakeTimeout time.Duration - idleConnTimeout time.Duration - expectContinueTimeout time.Duration - backoffMinTimeout time.Duration - backoffMaxTimeout time.Duration - backoffFactor int -} - -// ClientTimeout returns the corresponding private value. -func (c *HTTP) ClientTimeout() time.Duration { - return c.clientTimeout -} - -// DialTimeout returns the corresponding private value. -func (c *HTTP) DialTimeout() time.Duration { - return c.dialTimeout -} - -// KeepAlive returns the corresponding private value. -func (c *HTTP) KeepAlive() time.Duration { - return c.keepAlive -} - -// TLSHandshakeTimeout returns the corresponding private value. -func (c *HTTP) TLSHandshakeTimeout() time.Duration { - return c.tLSHandshakeTimeout -} - -// IdleConnTimeout returns the corresponding private value. -func (c *HTTP) IdleConnTimeout() time.Duration { - return c.idleConnTimeout -} - -// ExpectContinueTimeout returns the corresponding private value. -func (c *HTTP) ExpectContinueTimeout() time.Duration { - return c.expectContinueTimeout -} - -// BackoffMinTimeout returns the corresponding private value. -func (c *HTTP) BackoffMinTimeout() time.Duration { - return c.backoffMinTimeout -} - -// BackoffMaxTimeout returns the corresponding private value. -func (c *HTTP) BackoffMaxTimeout() time.Duration { - return c.backoffMaxTimeout -} - -// BackoffFactor returns the corresponding private value. -func (c *HTTP) BackoffFactor() int { - return c.backoffFactor -} - -// OpOutType represents type of output of Operation. -type OpOutType int - -const ( - OpJSON OpOutType = iota - OpRawBytes - OpFileList -) - -// OpParamType represents type of OpParams of Operation. -type OpParamsType int - -const ( - OpParamsEmpty OpParamsType = iota - OpParamsConfig - OpParamsAPI -) - -// Operation represents a single operation. -// -// An Operation represents a high level structure. -// Operation -> Task -> Task Executor -> Plugin -> Output. -type Operation struct { - Name string - Endpoint string - SendMethod string - Params OpParams - OutType OpOutType - Timeout time.Duration - SaveToFile bool - TaskMap map[string]string -} - -// OpParams represents params for an Operation. -type OpParams struct { - Key string - Template string - Type OpParamsType - Required bool + Port string + GuidelineFile string + GuidelineContentFile string + GoalFile string + GoalContentFile string + LogFile string } diff --git a/pkg/config/variables.go b/pkg/config/variables.go deleted file mode 100644 index e6c6967..0000000 --- a/pkg/config/variables.go +++ /dev/null @@ -1,105 +0,0 @@ -package config - -import ( - "time" -) - -const ( - EPCompanyConfiguration = "companyConfiguration" - EPConnections = "connections" - EPFile = "file" - EPFileSearch = "fileSearch" - EPFileSystem = "fileSystem" - EPLog = "log" - EPRegister = "register" - EPReport = "report" - - OPReport = "Report" - OPETCDir = "ETCDir" - OPIIS = "IIS" - OPRegistry = "Registry" - OPFileSearch = "FileSearch" - OPFileSystem = "FileSystem" - OPConnMap = "ConnMap" - - OPConnMapRunOnce = false -) - -const ( - opReportTimeout = 5 * time.Minute - opFileSearchTimeout = 10 * time.Hour - opFileSystemTimeout = 10 * time.Hour - opCollectFilesTimeout = 10 * time.Minute - opConnMapTimeout = 12 * time.Hour - - opReportParamsRequired = false - opETCDirParamsRequired = false - opIISParamsRequired = false - opRegistryParamsRequired = false - opFileSearchParamsRequired = true - opFileSystemParamsRequired = false - opConnMapParamsRequired = true - - opReportSaveToFile = true - opETCDirSaveToFile = true - opIISSaveToFile = true - opRegistrySaveToFile = true - opFileSearchSaveToFile = true - opFileSystemSaveToFile = false - opConnMapSaveToFile = true - - opConnMapTemplate = `{"duration":%d,"runOnce":%t}` -) - -var ( - opReportTaskMap = map[string]string{ - "AWS": "AWS", - "CronJobs": "CronJobs", - "Diskspaces": "Diskspaces", - "DNS": "DNS", - "Docker": "Docker", - "ENV": "Environment", - "Firewall": "Firewall", - "Fstab": "FSTab", - "Hostname": "Hostname", - "Hosts": "Hosts", - "LinuxRepositories": "LinRepos", - "ListenPorts": "ListenConn", - "Mounts": "Mounts", - "ActiveConnections": "NetConn", - "Network": "Network", - "Os": "OS", - "Packages": "Packages", - "Platform": "Platform", - "Processes": "Process", - "Routes": "Routes", - "Services": "Services", - "SysInfo": "SysInfo", - "TrafRules": "TrafRules", - "UserInfo": "UserInfo", - } - - opETCDirTaskMap = map[string]string{ - "ETCDir": "ETCDir", - } - - opIISTaskMap = map[string]string{ - "IIS": "IIS", - } - - opRegistryTaskMap = map[string]string{ - "Registry": "Registry", - } - - opFileSearchTaskMap = map[string]string{ - "FileSearch": "FileSearch", - } - - opFileSystemTaskMap = map[string]string{ - "FileSystem": "FileSystem", - } - - opConnMapTaskMap = map[string]string{ - "ConnMap": "ConnMap", - } -) diff --git a/pkg/config/variables_posix.go b/pkg/config/variables_posix.go deleted file mode 100644 index 930ed09..0000000 --- a/pkg/config/variables_posix.go +++ /dev/null @@ -1,80 +0,0 @@ -// +build linux darwin - -package config - -import ( - "net/http" -) - -var ( - operationsList = []Operation{ - Operation{ - Name: OPReport, - Endpoint: EPReport, - SendMethod: http.MethodPost, - Params: OpParams{ - Type: OpParamsEmpty, - Required: opReportParamsRequired, - }, - OutType: OpJSON, - Timeout: opReportTimeout, - SaveToFile: opReportSaveToFile, - TaskMap: opReportTaskMap, - }, - Operation{ - Name: OPETCDir, - Endpoint: EPFile, - SendMethod: http.MethodPut, - Params: OpParams{ - Type: OpParamsEmpty, - Required: opETCDirParamsRequired, - }, - OutType: OpFileList, - Timeout: opCollectFilesTimeout, - SaveToFile: opETCDirSaveToFile, - TaskMap: opETCDirTaskMap, - }, - Operation{ - Name: OPFileSearch, - Endpoint: EPFileSearch, - SendMethod: http.MethodPost, - Params: OpParams{ - Type: OpParamsAPI, - Required: opFileSearchParamsRequired, - Key: EPCompanyConfiguration, - }, - OutType: OpJSON, - Timeout: opFileSearchTimeout, - SaveToFile: opFileSearchSaveToFile, - TaskMap: opFileSearchTaskMap, - }, - Operation{ - Name: OPFileSystem, - Endpoint: EPFileSystem, - SendMethod: http.MethodPost, - Params: OpParams{ - Type: OpParamsEmpty, - Required: opFileSystemParamsRequired, - }, - OutType: OpRawBytes, - Timeout: opFileSearchTimeout, - SaveToFile: opFileSystemSaveToFile, - TaskMap: opFileSystemTaskMap, - }, - Operation{ - Name: OPConnMap, - Endpoint: EPConnections, - SendMethod: http.MethodPost, - Params: OpParams{ - Type: OpParamsConfig, - Required: opConnMapParamsRequired, - Key: OPConnMap, - Template: opConnMapTemplate, - }, - OutType: OpJSON, - Timeout: opConnMapTimeout, - SaveToFile: opConnMapSaveToFile, - TaskMap: opConnMapTaskMap, - }, - } -) diff --git a/pkg/config/variables_windows.go b/pkg/config/variables_windows.go deleted file mode 100644 index 0921660..0000000 --- a/pkg/config/variables_windows.go +++ /dev/null @@ -1,91 +0,0 @@ -package config - -import ( - "net/http" -) - -var ( - operationsList = []Operation{ - Operation{ - Name: OPReport, - Endpoint: EPReport, - SendMethod: http.MethodPost, - Params: OpParams{ - Type: OpParamsEmpty, - Required: opReportParamsRequired, - }, - OutType: OpJSON, - Timeout: opReportTimeout, - SaveToFile: opReportSaveToFile, - TaskMap: opReportTaskMap, - }, - Operation{ - Name: OPIIS, - Endpoint: EPFile, - SendMethod: http.MethodPut, - Params: OpParams{ - Type: OpParamsEmpty, - Required: opIISParamsRequired, - }, - OutType: OpFileList, - Timeout: opCollectFilesTimeout, - SaveToFile: opIISSaveToFile, - TaskMap: opIISTaskMap, - }, - Operation{ - Name: OPRegistry, - Endpoint: EPFile, - SendMethod: http.MethodPut, - Params: OpParams{ - Type: OpParamsEmpty, - Required: opRegistryParamsRequired, - }, - OutType: OpFileList, - Timeout: opCollectFilesTimeout, - SaveToFile: opRegistrySaveToFile, - TaskMap: opRegistryTaskMap, - }, - Operation{ - Name: OPFileSearch, - Endpoint: EPFileSearch, - SendMethod: http.MethodPost, - Params: OpParams{ - Type: OpParamsAPI, - Required: opFileSearchParamsRequired, - Key: EPCompanyConfiguration, - }, - OutType: OpJSON, - Timeout: opFileSearchTimeout, - SaveToFile: opFileSearchSaveToFile, - TaskMap: opFileSearchTaskMap, - }, - Operation{ - Name: OPFileSystem, - Endpoint: EPFileSystem, - SendMethod: http.MethodPost, - Params: OpParams{ - Type: OpParamsEmpty, - Required: opFileSystemParamsRequired, - }, - OutType: OpRawBytes, - Timeout: opFileSearchTimeout, - SaveToFile: opFileSystemSaveToFile, - TaskMap: opFileSystemTaskMap, - }, - Operation{ - Name: OPConnMap, - Endpoint: EPConnections, - SendMethod: http.MethodPost, - Params: OpParams{ - Type: OpParamsConfig, - Required: opConnMapParamsRequired, - Key: OPConnMap, - Template: opConnMapTemplate, - }, - OutType: OpJSON, - Timeout: opConnMapTimeout, - SaveToFile: opConnMapSaveToFile, - TaskMap: opConnMapTaskMap, - }, - } -) diff --git a/pkg/engine/lifestyle.go b/pkg/engine/lifestyle.go index 3d010a1..dc8d3f1 100644 --- a/pkg/engine/lifestyle.go +++ b/pkg/engine/lifestyle.go @@ -143,11 +143,13 @@ func (a *AlcoholGuidelines) Process(units float64, gender string) (Response, err // PhysicalActivityCondition object type PhysicalActivityCondition struct { - From *int `json:"from"` - To *int `json:"to"` - Unit *string `json:"unit"` - Type *string `json:"type"` - Target *string `json:"target"` + Gender *string `json:"gender"` + Age *RangeFloat `json:"age"` + From *int `json:"from"` + To *int `json:"to"` + Unit *string `json:"unit"` + Type *string `json:"type"` + Target *string `json:"target"` } // PhysicalActivityConditions slice @@ -165,13 +167,31 @@ type PhysicalActivityGuideline struct { type PhysicalActivityGuidelines []PhysicalActivityGuideline // Process function -func (p *PhysicalActivityGuidelines) Process(duration int) (Response, error) { +func (p *PhysicalActivityGuidelines) Process(duration int, gender string, age float64) (Response, error) { code := "" value := fmt.Sprintf("%d minutes", duration) target := "" + if gender == "m" { + gender = "male" + } else { + gender = "female" + } + for _, g := range *p { for _, c := range *g.Conditions { + ageFrom := 0.0 + ageTo := math.MaxFloat64 + + if c.Age != nil { + if c.Age.From != nil { + ageFrom = *c.Age.From + } + if c.Age.To != nil { + ageTo = *c.Age.To + } + } + from := 0 to := math.MaxInt32 if c.From != nil { @@ -180,7 +200,13 @@ func (p *PhysicalActivityGuidelines) Process(duration int) (Response, error) { if c.To != nil { to = tools.CalculateExercise(*c.To, *c.Unit, "weekly", *c.Type) } - if duration >= from && duration <= to { + + conditionGender := true + if c.Gender != nil && *c.Gender != gender { + conditionGender = false + } + + if conditionGender && (age >= ageFrom && age <= ageTo) && duration >= from && duration <= to { code = *g.Code target = *c.Target break diff --git a/pkg/service/service.go b/pkg/service/service.go index 9bac3ed..f40b983 100644 --- a/pkg/service/service.go +++ b/pkg/service/service.go @@ -14,6 +14,7 @@ import ( "github.com/openhealthalgorithms/service/pkg" "github.com/openhealthalgorithms/service/pkg/algorithms/hearts" + "github.com/openhealthalgorithms/service/pkg/config" "github.com/openhealthalgorithms/service/pkg/database" "github.com/openhealthalgorithms/service/pkg/tools" "github.com/openhealthalgorithms/service/pkg/types" @@ -48,7 +49,11 @@ type Service struct { // NewService method func NewService() Service { - return NewServiceWithPort("9595") + currentSettings := config.CurrentSettings() + + dbFile = currentSettings.LogFile + + return NewServiceWithPort(currentSettings.Port) } // NewServiceWithPort method @@ -135,12 +140,14 @@ func algorithmRequestHandler(w http.ResponseWriter, r *http.Request) { return } + currentSettings := config.CurrentSettings() + v := types.NewValuesCtx() v.Params.Set("params", paramObj) - v.Params.Set("guide", "guideline_hearts.json") - v.Params.Set("guidecontent", "guideline_hearts_content.json") - v.Params.Set("goal", "goals_hearts.json") - v.Params.Set("goalcontent", "goals_hearts_content.json") + v.Params.Set("guide", currentSettings.GuidelineFile) + v.Params.Set("guidecontent", currentSettings.GuidelineContentFile) + v.Params.Set("goal", currentSettings.GoalFile) + v.Params.Set("goalcontent", currentSettings.GoalContentFile) ctx := context.WithValue(context.Background(), types.KeyValuesCtx, &v) diff --git a/pkg/version.go b/pkg/version.go index bd1778a..9dd3a75 100644 --- a/pkg/version.go +++ b/pkg/version.go @@ -1,6 +1,6 @@ package pkg -const version = "v0.4.8" +const version = "v0.5.0" // GetVersion returns the current version func GetVersion() string {