pipelineservice_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package customcost
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "os"
  7. "runtime"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/hashicorp/go-plugin"
  12. "github.com/opencost/opencost/core/pkg/log"
  13. "github.com/opencost/opencost/core/pkg/util/timeutil"
  14. )
  15. func TestPipelineService(t *testing.T) {
  16. // establish temporary test assets dir
  17. dir := t.TempDir()
  18. err := os.MkdirAll(dir+"/config", 0777)
  19. if err != nil {
  20. t.Fatalf("error creating temp config dir: %v", err)
  21. }
  22. err = os.MkdirAll(dir+"/executable", 0777)
  23. if err != nil {
  24. t.Fatalf("error creating temp exec dir: %v", err)
  25. }
  26. // write DD secrets to config files
  27. // write config file to temp dir
  28. writeDDConfig(dir+"/config", t)
  29. // set env vars for plugin config and executable
  30. err = os.Setenv("PLUGIN_CONFIG_DIR", dir+"/config")
  31. if err != nil {
  32. t.Fatalf("error setting config dir env var: %v", err)
  33. }
  34. err = os.Setenv("PLUGIN_EXECUTABLE_DIR", dir+"/executable")
  35. if err != nil {
  36. t.Fatalf("error setting config dir env var: %v", err)
  37. }
  38. // download amd plugin, store in tmp executable dir
  39. downloadLatestPluginExec(dir+"/executable", t)
  40. // set up repos
  41. hourlyRepo := NewMemoryRepository()
  42. dailyRepo := NewMemoryRepository()
  43. // set up ingestor config
  44. config := DefaultIngestorConfiguration()
  45. config.DailyDuration = 7 * timeutil.Day
  46. config.HourlyDuration = 16 * time.Hour
  47. pipeline, err := NewPipelineService(hourlyRepo, dailyRepo, config)
  48. if err != nil {
  49. t.Fatalf("error starting pipeline: %v", err)
  50. }
  51. // wait until coverage is complete, then stop ingestor
  52. ingestionComplete := false
  53. maxLoops := 10
  54. loopCount := 0
  55. for !ingestionComplete && loopCount < maxLoops {
  56. status := pipeline.Status()
  57. log.Debugf("got status: %v", status)
  58. coverageHourly, foundHourly := status.CoverageHourly["datadog"]
  59. coverageDaily, foundDaily := status.CoverageDaily["datadog"]
  60. if foundHourly && foundDaily {
  61. // check coverage
  62. minTime := time.Now().UTC().Add(-6 * timeutil.Day)
  63. maxTime := time.Now().UTC().Add(-3 * time.Hour)
  64. if coverageDaily.Start().Before(minTime) && coverageHourly.End().After(maxTime) {
  65. log.Infof("good coverage, breaking out of loop")
  66. ingestionComplete = true
  67. break
  68. } else {
  69. log.Infof("coverage not within range. Looking for coverage %v to %v, but current coverage is %v/%v", minTime, maxTime, coverageDaily, coverageHourly)
  70. }
  71. } else {
  72. log.Debugf("no coverage info ready yet for datadog")
  73. }
  74. log.Infof("sleeping 10s...")
  75. time.Sleep(10 * time.Second)
  76. loopCount++
  77. }
  78. if !ingestionComplete {
  79. t.Fatal("ingestor never completed within allocated time")
  80. }
  81. pipeline.hourlyIngestor.Stop()
  82. pipeline.dailyIngestor.Stop()
  83. // inspect data from yesterday
  84. targetTime := time.Now().UTC().Add(-1 * timeutil.Day).Truncate(timeutil.Day)
  85. log.Infof("querying for data with window start: %v", targetTime)
  86. // check for presence of hosts in DD response
  87. ddCosts, err := dailyRepo.Get(targetTime, "datadog")
  88. if err != nil {
  89. t.Fatalf("error getting results for targetTime")
  90. }
  91. foundInfraHosts := false
  92. for _, cost := range ddCosts.Costs {
  93. if cost.ResourceType == "infra_hosts" {
  94. foundInfraHosts = true
  95. }
  96. }
  97. if !foundInfraHosts {
  98. t.Fatal("expecting infra_hosts costs in daily response")
  99. }
  100. // query data from 4 hours ago (hourly)
  101. targetTime = time.Now().UTC().Add(-13 * time.Hour).Truncate(time.Hour)
  102. log.Infof("querying for data with window start: %v", targetTime)
  103. // check for presence of hosts in DD response
  104. ddCosts, err = hourlyRepo.Get(targetTime, "datadog")
  105. if err != nil {
  106. t.Fatalf("error getting results for targetTime")
  107. }
  108. foundInfraHosts = false
  109. for _, cost := range ddCosts.Costs {
  110. if cost.ResourceType == "infra_hosts" {
  111. foundInfraHosts = true
  112. }
  113. }
  114. if !foundInfraHosts {
  115. t.Fatal("expecting infra_hosts costs in hourly response")
  116. }
  117. }
  118. func downloadLatestPluginExec(dirName string, t *testing.T) {
  119. ddPluginURL := "https://github.com/opencost/opencost-plugins/releases/download/v0.0.3/datadog.ocplugin." + runtime.GOOS + "." + runtime.GOARCH
  120. out, err := os.OpenFile(dirName+"/datadog.ocplugin."+runtime.GOOS+"."+runtime.GOARCH, 0755|os.O_CREATE, 0755)
  121. if err != nil {
  122. t.Fatalf("error creating executable file: %v", err)
  123. }
  124. resp, err := http.Get(ddPluginURL)
  125. if err != nil {
  126. t.Fatalf("error downloading: %v", err)
  127. }
  128. defer resp.Body.Close()
  129. defer out.Close()
  130. _, err = io.Copy(out, resp.Body)
  131. if err != nil {
  132. t.Fatalf("error copying: %v", err)
  133. }
  134. }
  135. func TestGetRegisteredPlugins_UnreadableConfigDir(t *testing.T) {
  136. testCases := []struct {
  137. name string
  138. setupFunc func() (configDir string, execDir string, cleanup func())
  139. expectError bool
  140. errorContains string
  141. }{
  142. {
  143. name: "non-existent config directory",
  144. setupFunc: func() (string, string, func()) {
  145. execDir := t.TempDir()
  146. return "/non/existent/path", execDir, func() {}
  147. },
  148. expectError: true,
  149. errorContains: "failed to read plugin config directory",
  150. },
  151. {
  152. name: "config directory is a file not a directory",
  153. setupFunc: func() (string, string, func()) {
  154. tmpDir := t.TempDir()
  155. execDir := t.TempDir()
  156. // Create a file instead of a directory
  157. configFile := tmpDir + "/not-a-directory"
  158. err := os.WriteFile(configFile, []byte("test"), 0644)
  159. if err != nil {
  160. t.Fatalf("failed to create test file: %v", err)
  161. }
  162. return configFile, execDir, func() {}
  163. },
  164. expectError: true,
  165. errorContains: "failed to read plugin config directory",
  166. },
  167. {
  168. name: "empty valid config directory",
  169. setupFunc: func() (string, string, func()) {
  170. configDir := t.TempDir()
  171. execDir := t.TempDir()
  172. return configDir, execDir, func() {}
  173. },
  174. expectError: false,
  175. errorContains: "",
  176. },
  177. }
  178. for _, tc := range testCases {
  179. t.Run(tc.name, func(t *testing.T) {
  180. configDir, execDir, cleanup := tc.setupFunc()
  181. defer cleanup()
  182. _, err := getRegisteredPlugins(configDir, execDir)
  183. if tc.expectError {
  184. if err == nil {
  185. t.Errorf("expected error but got nil")
  186. } else if tc.errorContains != "" && !strings.Contains(err.Error(), tc.errorContains) {
  187. t.Errorf("expected error to contain %q, but got: %v", tc.errorContains, err)
  188. }
  189. } else {
  190. if err != nil {
  191. t.Errorf("expected no error but got: %v", err)
  192. }
  193. }
  194. })
  195. }
  196. }
  197. func writeDDConfig(pluginConfigDir string, t *testing.T) {
  198. // read necessary env vars. If any are missing, log warning and skip test
  199. ddSite := os.Getenv("DD_SITE")
  200. ddApiKey := os.Getenv("DD_API_KEY")
  201. ddAppKey := os.Getenv("DD_APPLICATION_KEY")
  202. if ddSite == "" {
  203. log.Warnf("DD_SITE undefined, this needs to have the URL of your DD instance, skipping test")
  204. t.Skip()
  205. return
  206. }
  207. if ddApiKey == "" {
  208. log.Warnf("DD_API_KEY undefined, skipping test")
  209. t.Skip()
  210. return
  211. }
  212. if ddAppKey == "" {
  213. log.Warnf("DD_APPLICATION_KEY undefined, skipping test")
  214. t.Skip()
  215. return
  216. }
  217. // write out config to temp file using contents of env vars
  218. ddConf := fmt.Sprintf(`{"datadog_site": "%s", "datadog_api_key": "%s", "datadog_app_key": "%s"}`, ddSite, ddApiKey, ddAppKey)
  219. // set up custom cost request
  220. file, err := os.CreateTemp(pluginConfigDir, "datadog_config.json")
  221. if err != nil {
  222. t.Fatalf("could not create temp config dir: %v", err)
  223. }
  224. err = os.WriteFile(file.Name(), []byte(ddConf), 0777)
  225. if err != nil {
  226. t.Fatalf("could not write file: %v", err)
  227. }
  228. }
  229. // TestPipelineService_Stop_Nil ensures nil PipelineService is safe
  230. func TestPipelineService_Stop_Nil(t *testing.T) {
  231. var ps *PipelineService
  232. ps.Stop()
  233. t.Log("Nil PipelineService handled safely")
  234. }
  235. // TestPipelineService_Stop_WithNilIngestors ensures nil ingestors are handled
  236. func TestPipelineService_Stop_WithNilIngestors(t *testing.T) {
  237. ps := &PipelineService{
  238. hourlyIngestor: nil,
  239. dailyIngestor: nil,
  240. domains: []string{},
  241. }
  242. ps.Stop()
  243. t.Log("Nil ingestors handled safely")
  244. }
  245. // TestPipelineService_Stop_PartialNilIngestors ensures partial nil is handled
  246. func TestPipelineService_Stop_PartialNilIngestors(t *testing.T) {
  247. hourly := &CustomCostIngestor{
  248. key: "hourly",
  249. plugins: make(map[string]*plugin.Client),
  250. }
  251. ps := &PipelineService{
  252. hourlyIngestor: hourly,
  253. dailyIngestor: nil,
  254. domains: []string{},
  255. }
  256. ps.Stop()
  257. t.Log("Partial nil ingestors handled safely")
  258. }
  259. // TestPipelineService_Stop_ShutdownLogging verifies logging during shutdown
  260. func TestPipelineService_Stop_ShutdownLogging(t *testing.T) {
  261. ps := &PipelineService{
  262. hourlyIngestor: &CustomCostIngestor{
  263. key: "hourly",
  264. plugins: make(map[string]*plugin.Client),
  265. },
  266. dailyIngestor: &CustomCostIngestor{
  267. key: "daily",
  268. plugins: make(map[string]*plugin.Client),
  269. },
  270. domains: []string{},
  271. }
  272. ps.Stop()
  273. time.Sleep(50 * time.Millisecond)
  274. t.Log("Pipeline service logged shutdown progress")
  275. }
  276. func TestPipelineService_Stop_NilReceiver(t *testing.T) {
  277. var ps *PipelineService
  278. ps.Stop() // should not panic on nil receiver
  279. }
  280. func TestPipelineService_Stop_NilIngestors(t *testing.T) {
  281. ps := &PipelineService{}
  282. ps.Stop() // should not panic when ingestors are nil
  283. }
  284. func TestPipelineService_Stop_WithIngestors(t *testing.T) {
  285. hourly := &CustomCostIngestor{plugins: map[string]*plugin.Client{}}
  286. daily := &CustomCostIngestor{plugins: map[string]*plugin.Client{}}
  287. ps := &PipelineService{
  288. hourlyIngestor: hourly,
  289. dailyIngestor: daily,
  290. }
  291. ps.Stop()
  292. }
  293. func TestPipelineService_Stop_OnlyHourlyIngestor(t *testing.T) {
  294. ps := &PipelineService{
  295. hourlyIngestor: &CustomCostIngestor{plugins: map[string]*plugin.Client{}},
  296. }
  297. ps.Stop() // should not panic when dailyIngestor is nil
  298. }
  299. func TestPipelineService_Stop_OnlyDailyIngestor(t *testing.T) {
  300. ps := &PipelineService{
  301. dailyIngestor: &CustomCostIngestor{plugins: map[string]*plugin.Client{}},
  302. }
  303. ps.Stop() // should not panic when hourlyIngestor is nil
  304. }