provider.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. package cloud
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/url"
  10. "os"
  11. "reflect"
  12. "strings"
  13. "k8s.io/klog"
  14. "cloud.google.com/go/compute/metadata"
  15. v1 "k8s.io/api/core/v1"
  16. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  17. "k8s.io/client-go/kubernetes"
  18. )
  19. const clusterIDKey = "CLUSTER_ID"
  20. const remoteEnabled = "REMOTE_WRITE_ENABLED"
  21. const remotePW = "REMOTE_WRITE_PASSWORD"
  22. const sqlAddress = "SQL_ADDRESS"
  23. var createTableStatements = []string{
  24. `CREATE TABLE IF NOT EXISTS names (
  25. cluster_id VARCHAR(255) NOT NULL,
  26. cluster_name VARCHAR(255) NULL,
  27. PRIMARY KEY (cluster_id)
  28. );`,
  29. }
  30. // Node is the interface by which the provider and cost model communicate Node prices.
  31. // The provider will best-effort try to fill out this struct.
  32. type Node struct {
  33. Cost string `json:"hourlyCost"`
  34. VCPU string `json:"CPU"`
  35. VCPUCost string `json:"CPUHourlyCost"`
  36. RAM string `json:"RAM"`
  37. RAMBytes string `json:"RAMBytes"`
  38. RAMCost string `json:"RAMGBHourlyCost"`
  39. Storage string `json:"storage"`
  40. StorageCost string `json:"storageHourlyCost"`
  41. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  42. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  43. BaseRAMPrice string `json:"baseRAMPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  44. BaseGPUPrice string `json:"baseGPUPrice"`
  45. UsageType string `json:"usageType"`
  46. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  47. GPUName string `json:"gpuName"`
  48. GPUCost string `json:"gpuCost"`
  49. }
  50. // IsSpot determines whether or not a Node uses spot by usage type
  51. func (n *Node) IsSpot() bool {
  52. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  53. }
  54. // Network is the interface by which the provider and cost model communicate network egress prices.
  55. // The provider will best-effort try to fill out this struct.
  56. type Network struct {
  57. ZoneNetworkEgressCost float64
  58. RegionNetworkEgressCost float64
  59. InternetNetworkEgressCost float64
  60. }
  61. // PV is the interface by which the provider and cost model communicate PV prices.
  62. // The provider will best-effort try to fill out this struct.
  63. type PV struct {
  64. Cost string `json:"hourlyCost"`
  65. CostPerIO string `json:"costPerIOOperation"`
  66. Class string `json:"storageClass"`
  67. Size string `json:"size"`
  68. Region string `json:"region"`
  69. Parameters map[string]string `json:"parameters"`
  70. }
  71. // Key represents a way for nodes to match between the k8s API and a pricing API
  72. type Key interface {
  73. ID() string // ID represents an exact match
  74. Features() string // Features are a comma separated string of node metadata that could match pricing
  75. GPUType() string // GPUType returns "" if no GPU exists, but the name of the GPU otherwise
  76. }
  77. type PVKey interface {
  78. Features() string
  79. GetStorageClass() string
  80. }
  81. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  82. type OutOfClusterAllocation struct {
  83. Aggregator string `json:"aggregator"`
  84. Environment string `json:"environment"`
  85. Service string `json:"service"`
  86. Cost float64 `json:"cost"`
  87. Cluster string `json:"cluster"`
  88. }
  89. type CustomPricing struct {
  90. Provider string `json:"provider"`
  91. Description string `json:"description"`
  92. CPU string `json:"CPU"`
  93. SpotCPU string `json:"spotCPU"`
  94. RAM string `json:"RAM"`
  95. SpotRAM string `json:"spotRAM"`
  96. GPU string `json:"GPU"`
  97. SpotGPU string `json:"spotGPU"`
  98. Storage string `json:"storage"`
  99. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  100. RegionNetworkEgress string `json:"regionNetworkEgress"`
  101. InternetNetworkEgress string `json:"internetNetworkEgress"`
  102. SpotLabel string `json:"spotLabel,omitempty"`
  103. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  104. GpuLabel string `json:"gpuLabel,omitempty"`
  105. GpuLabelValue string `json:"gpuLabelValue,omitempty"`
  106. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  107. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  108. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  109. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  110. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  111. ProjectID string `json:"projectID,omitempty"`
  112. AthenaBucketName string `json:"athenaBucketName"`
  113. AthenaRegion string `json:"athenaRegion"`
  114. AthenaDatabase string `json:"athenaDatabase"`
  115. AthenaTable string `json:"athenaTable"`
  116. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  117. CustomPricesEnabled string `json:"customPricesEnabled"`
  118. AzureSubscriptionID string `json:"azureSubscriptionID"`
  119. AzureClientID string `json:"azureClientID"`
  120. AzureClientSecret string `json:"azureClientSecret"`
  121. AzureTenantID string `json:"azureTenantID"`
  122. AzureBillingRegion string `json:"azureBillingRegion"`
  123. CurrencyCode string `json:"currencyCode"`
  124. Discount string `json:"discount"`
  125. ClusterName string `json:"clusterName"`
  126. }
  127. // Provider represents a k8s provider.
  128. type Provider interface {
  129. ClusterInfo() (map[string]string, error)
  130. AddServiceKey(url.Values) error
  131. GetDisks() ([]byte, error)
  132. NodePricing(Key) (*Node, error)
  133. PVPricing(PVKey) (*PV, error)
  134. NetworkPricing() (*Network, error)
  135. AllNodePricing() (interface{}, error)
  136. DownloadPricingData() error
  137. GetKey(map[string]string) Key
  138. GetPVKey(*v1.PersistentVolume, map[string]string) PVKey
  139. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  140. GetConfig() (*CustomPricing, error)
  141. GetManagementPlatform() (string, error)
  142. GetLocalStorageQuery(offset string) (string, error)
  143. ExternalAllocations(string, string, string) ([]*OutOfClusterAllocation, error)
  144. }
  145. // ClusterName returns the name defined in cluster info, defaulting to the
  146. // CLUSTER_ID environment variable
  147. func ClusterName(p Provider) string {
  148. info, err := p.ClusterInfo()
  149. if err != nil {
  150. return os.Getenv(clusterIDKey)
  151. }
  152. name, ok := info["name"]
  153. if !ok {
  154. return os.Getenv(clusterIDKey)
  155. }
  156. return name
  157. }
  158. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  159. // indicating whether or not the cluster is using custom pricing.
  160. func CustomPricesEnabled(p Provider) bool {
  161. config, err := p.GetConfig()
  162. if err != nil {
  163. return false
  164. }
  165. return config.CustomPricesEnabled == "true"
  166. }
  167. // GetDefaultPricingData will search for a json file representing pricing data in /models/ and use it for base pricing info.
  168. func GetDefaultPricingData(fname string) (*CustomPricing, error) {
  169. path := os.Getenv("CONFIG_PATH")
  170. if path == "" {
  171. path = "/models/"
  172. }
  173. path += fname
  174. if _, err := os.Stat(path); err == nil {
  175. jsonFile, err := os.Open(path)
  176. if err != nil {
  177. return nil, err
  178. }
  179. defer jsonFile.Close()
  180. byteValue, err := ioutil.ReadAll(jsonFile)
  181. if err != nil {
  182. return nil, err
  183. }
  184. var customPricing = &CustomPricing{}
  185. err = json.Unmarshal([]byte(byteValue), customPricing)
  186. if err != nil {
  187. return nil, err
  188. }
  189. return customPricing, nil
  190. } else if os.IsNotExist(err) {
  191. c := &CustomPricing{
  192. Provider: fname,
  193. Description: "Default prices based on GCP us-central1",
  194. CPU: "0.031611",
  195. SpotCPU: "0.006655",
  196. RAM: "0.004237",
  197. SpotRAM: "0.000892",
  198. GPU: "0.95",
  199. Storage: "0.00005479452",
  200. ZoneNetworkEgress: "0.01",
  201. RegionNetworkEgress: "0.01",
  202. InternetNetworkEgress: "0.12",
  203. CustomPricesEnabled: "false",
  204. }
  205. cj, err := json.Marshal(c)
  206. if err != nil {
  207. return nil, err
  208. }
  209. err = ioutil.WriteFile(path, cj, 0644)
  210. if err != nil {
  211. return nil, err
  212. }
  213. return c, nil
  214. } else {
  215. return nil, err
  216. }
  217. }
  218. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  219. structValue := reflect.ValueOf(obj).Elem()
  220. structFieldValue := structValue.FieldByName(name)
  221. if !structFieldValue.IsValid() {
  222. return fmt.Errorf("No such field: %s in obj", name)
  223. }
  224. if !structFieldValue.CanSet() {
  225. return fmt.Errorf("Cannot set %s field value", name)
  226. }
  227. structFieldType := structFieldValue.Type()
  228. val := reflect.ValueOf(value)
  229. if structFieldType != val.Type() {
  230. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  231. }
  232. structFieldValue.Set(val)
  233. return nil
  234. }
  235. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  236. func NewProvider(clientset *kubernetes.Clientset, apiKey string) (Provider, error) {
  237. if metadata.OnGCE() {
  238. klog.V(3).Info("metadata reports we are in GCE")
  239. if apiKey == "" {
  240. return nil, errors.New("Supply a GCP Key to start getting data")
  241. }
  242. return &GCP{
  243. Clientset: clientset,
  244. APIKey: apiKey,
  245. }, nil
  246. }
  247. nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  248. if err != nil {
  249. return nil, err
  250. }
  251. provider := strings.ToLower(nodes.Items[0].Spec.ProviderID)
  252. if strings.HasPrefix(provider, "aws") {
  253. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  254. return &AWS{
  255. Clientset: clientset,
  256. }, nil
  257. } else if strings.HasPrefix(provider, "azure") {
  258. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  259. return &Azure{
  260. Clientset: clientset,
  261. }, nil
  262. } else {
  263. klog.V(2).Info("Unsupported provider, falling back to default")
  264. return &CustomProvider{
  265. Clientset: clientset,
  266. }, nil
  267. }
  268. }
  269. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  270. pw := os.Getenv(remotePW)
  271. address := os.Getenv(sqlAddress)
  272. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  273. db, err := sql.Open("postgres", connStr)
  274. if err != nil {
  275. return err
  276. }
  277. defer db.Close()
  278. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  279. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  280. if err != nil {
  281. return err
  282. }
  283. return nil
  284. }
  285. func CreateClusterMeta(cluster_id, cluster_name string) error {
  286. pw := os.Getenv(remotePW)
  287. address := os.Getenv(sqlAddress)
  288. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  289. db, err := sql.Open("postgres", connStr)
  290. if err != nil {
  291. return err
  292. }
  293. defer db.Close()
  294. for _, stmt := range createTableStatements {
  295. _, err := db.Exec(stmt)
  296. if err != nil {
  297. return err
  298. }
  299. }
  300. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  301. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  302. if err != nil {
  303. return err
  304. }
  305. return nil
  306. }
  307. func GetClusterMeta(cluster_id string) (string, string, error) {
  308. pw := os.Getenv(remotePW)
  309. address := os.Getenv(sqlAddress)
  310. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  311. db, err := sql.Open("postgres", connStr)
  312. defer db.Close()
  313. query := `SELECT cluster_id, cluster_name
  314. FROM names
  315. WHERE cluster_id = ?`
  316. rows, err := db.Query(query, cluster_id)
  317. if err != nil {
  318. return "", "", err
  319. }
  320. defer rows.Close()
  321. var (
  322. sql_cluster_id string
  323. cluster_name string
  324. )
  325. for rows.Next() {
  326. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  327. return "", "", err
  328. }
  329. }
  330. return sql_cluster_id, cluster_name, nil
  331. }
  332. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  333. id, name, err := GetClusterMeta(cluster_id)
  334. if err != nil {
  335. err := CreateClusterMeta(cluster_id, cluster_name)
  336. if err != nil {
  337. return "", "", err
  338. }
  339. }
  340. if id == "" {
  341. err := CreateClusterMeta(cluster_id, cluster_name)
  342. if err != nil {
  343. return "", "", err
  344. }
  345. }
  346. return id, name, nil
  347. }