provider.go 11 KB

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