deployment.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. package ionet
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "github.com/samber/lo"
  7. )
  8. // DeployContainer deploys a new container with the specified configuration
  9. func (c *Client) DeployContainer(req *DeploymentRequest) (*DeploymentResponse, error) {
  10. if req == nil {
  11. return nil, fmt.Errorf("deployment request cannot be nil")
  12. }
  13. // Validate required fields
  14. if req.ResourcePrivateName == "" {
  15. return nil, fmt.Errorf("resource_private_name is required")
  16. }
  17. if len(req.LocationIDs) == 0 {
  18. return nil, fmt.Errorf("location_ids is required")
  19. }
  20. if req.HardwareID <= 0 {
  21. return nil, fmt.Errorf("hardware_id is required")
  22. }
  23. if req.RegistryConfig.ImageURL == "" {
  24. return nil, fmt.Errorf("registry_config.image_url is required")
  25. }
  26. if req.GPUsPerContainer < 1 {
  27. return nil, fmt.Errorf("gpus_per_container must be at least 1")
  28. }
  29. if req.DurationHours < 1 {
  30. return nil, fmt.Errorf("duration_hours must be at least 1")
  31. }
  32. if req.ContainerConfig.ReplicaCount < 1 {
  33. return nil, fmt.Errorf("container_config.replica_count must be at least 1")
  34. }
  35. resp, err := c.makeRequest("POST", "/deploy", req)
  36. if err != nil {
  37. return nil, fmt.Errorf("failed to deploy container: %w", err)
  38. }
  39. // API returns direct format:
  40. // {"status": "string", "deployment_id": "..."}
  41. var deployResp DeploymentResponse
  42. if err := json.Unmarshal(resp.Body, &deployResp); err != nil {
  43. return nil, fmt.Errorf("failed to parse deployment response: %w", err)
  44. }
  45. return &deployResp, nil
  46. }
  47. // ListDeployments retrieves a list of deployments with optional filtering
  48. func (c *Client) ListDeployments(opts *ListDeploymentsOptions) (*DeploymentList, error) {
  49. params := make(map[string]interface{})
  50. if opts != nil {
  51. params["status"] = opts.Status
  52. params["location_id"] = opts.LocationID
  53. params["page"] = opts.Page
  54. params["page_size"] = opts.PageSize
  55. params["sort_by"] = opts.SortBy
  56. params["sort_order"] = opts.SortOrder
  57. }
  58. endpoint := "/deployments" + buildQueryParams(params)
  59. resp, err := c.makeRequest("GET", endpoint, nil)
  60. if err != nil {
  61. return nil, fmt.Errorf("failed to list deployments: %w", err)
  62. }
  63. var deploymentList DeploymentList
  64. if err := decodeData(resp.Body, &deploymentList); err != nil {
  65. return nil, fmt.Errorf("failed to parse deployments list: %w", err)
  66. }
  67. deploymentList.Deployments = lo.Map(deploymentList.Deployments, func(deployment Deployment, _ int) Deployment {
  68. deployment.GPUCount = deployment.HardwareQuantity
  69. deployment.Replicas = deployment.HardwareQuantity // Assuming 1:1 mapping for now
  70. return deployment
  71. })
  72. return &deploymentList, nil
  73. }
  74. // GetDeployment retrieves detailed information about a specific deployment
  75. func (c *Client) GetDeployment(deploymentID string) (*DeploymentDetail, error) {
  76. if deploymentID == "" {
  77. return nil, fmt.Errorf("deployment ID cannot be empty")
  78. }
  79. endpoint := fmt.Sprintf("/deployment/%s", deploymentID)
  80. resp, err := c.makeRequest("GET", endpoint, nil)
  81. if err != nil {
  82. return nil, fmt.Errorf("failed to get deployment details: %w", err)
  83. }
  84. var deploymentDetail DeploymentDetail
  85. if err := decodeDataWithFlexibleTimes(resp.Body, &deploymentDetail); err != nil {
  86. return nil, fmt.Errorf("failed to parse deployment details: %w", err)
  87. }
  88. return &deploymentDetail, nil
  89. }
  90. // UpdateDeployment updates the configuration of an existing deployment
  91. func (c *Client) UpdateDeployment(deploymentID string, req *UpdateDeploymentRequest) (*UpdateDeploymentResponse, error) {
  92. if deploymentID == "" {
  93. return nil, fmt.Errorf("deployment ID cannot be empty")
  94. }
  95. if req == nil {
  96. return nil, fmt.Errorf("update request cannot be nil")
  97. }
  98. endpoint := fmt.Sprintf("/deployment/%s", deploymentID)
  99. resp, err := c.makeRequest("PATCH", endpoint, req)
  100. if err != nil {
  101. return nil, fmt.Errorf("failed to update deployment: %w", err)
  102. }
  103. // API returns direct format:
  104. // {"status": "string", "deployment_id": "..."}
  105. var updateResp UpdateDeploymentResponse
  106. if err := json.Unmarshal(resp.Body, &updateResp); err != nil {
  107. return nil, fmt.Errorf("failed to parse update deployment response: %w", err)
  108. }
  109. return &updateResp, nil
  110. }
  111. // ExtendDeployment extends the duration of an existing deployment
  112. func (c *Client) ExtendDeployment(deploymentID string, req *ExtendDurationRequest) (*DeploymentDetail, error) {
  113. if deploymentID == "" {
  114. return nil, fmt.Errorf("deployment ID cannot be empty")
  115. }
  116. if req == nil {
  117. return nil, fmt.Errorf("extend request cannot be nil")
  118. }
  119. if req.DurationHours < 1 {
  120. return nil, fmt.Errorf("duration_hours must be at least 1")
  121. }
  122. endpoint := fmt.Sprintf("/deployment/%s/extend", deploymentID)
  123. resp, err := c.makeRequest("POST", endpoint, req)
  124. if err != nil {
  125. return nil, fmt.Errorf("failed to extend deployment: %w", err)
  126. }
  127. var deploymentDetail DeploymentDetail
  128. if err := decodeDataWithFlexibleTimes(resp.Body, &deploymentDetail); err != nil {
  129. return nil, fmt.Errorf("failed to parse extended deployment details: %w", err)
  130. }
  131. return &deploymentDetail, nil
  132. }
  133. // DeleteDeployment deletes an active deployment
  134. func (c *Client) DeleteDeployment(deploymentID string) (*UpdateDeploymentResponse, error) {
  135. if deploymentID == "" {
  136. return nil, fmt.Errorf("deployment ID cannot be empty")
  137. }
  138. endpoint := fmt.Sprintf("/deployment/%s", deploymentID)
  139. resp, err := c.makeRequest("DELETE", endpoint, nil)
  140. if err != nil {
  141. return nil, fmt.Errorf("failed to delete deployment: %w", err)
  142. }
  143. // API returns direct format:
  144. // {"status": "string", "deployment_id": "..."}
  145. var deleteResp UpdateDeploymentResponse
  146. if err := json.Unmarshal(resp.Body, &deleteResp); err != nil {
  147. return nil, fmt.Errorf("failed to parse delete deployment response: %w", err)
  148. }
  149. return &deleteResp, nil
  150. }
  151. // GetPriceEstimation calculates the estimated cost for a deployment
  152. func (c *Client) GetPriceEstimation(req *PriceEstimationRequest) (*PriceEstimationResponse, error) {
  153. if req == nil {
  154. return nil, fmt.Errorf("price estimation request cannot be nil")
  155. }
  156. // Validate required fields
  157. if len(req.LocationIDs) == 0 {
  158. return nil, fmt.Errorf("location_ids is required")
  159. }
  160. if req.HardwareID == 0 {
  161. return nil, fmt.Errorf("hardware_id is required")
  162. }
  163. if req.ReplicaCount < 1 {
  164. return nil, fmt.Errorf("replica_count must be at least 1")
  165. }
  166. currency := strings.TrimSpace(req.Currency)
  167. if currency == "" {
  168. currency = "usdc"
  169. }
  170. durationType := strings.TrimSpace(req.DurationType)
  171. if durationType == "" {
  172. durationType = "hour"
  173. }
  174. durationType = strings.ToLower(durationType)
  175. apiDurationType := ""
  176. durationQty := req.DurationQty
  177. if durationQty < 1 {
  178. durationQty = req.DurationHours
  179. }
  180. if durationQty < 1 {
  181. return nil, fmt.Errorf("duration_qty must be at least 1")
  182. }
  183. hardwareQty := req.HardwareQty
  184. if hardwareQty < 1 {
  185. hardwareQty = req.GPUsPerContainer
  186. }
  187. if hardwareQty < 1 {
  188. return nil, fmt.Errorf("hardware_qty must be at least 1")
  189. }
  190. durationHoursForRate := req.DurationHours
  191. if durationHoursForRate < 1 {
  192. durationHoursForRate = durationQty
  193. }
  194. switch durationType {
  195. case "hour", "hours", "hourly":
  196. durationHoursForRate = durationQty
  197. apiDurationType = "hourly"
  198. case "day", "days", "daily":
  199. durationHoursForRate = durationQty * 24
  200. apiDurationType = "daily"
  201. case "week", "weeks", "weekly":
  202. durationHoursForRate = durationQty * 24 * 7
  203. apiDurationType = "weekly"
  204. case "month", "months", "monthly":
  205. durationHoursForRate = durationQty * 24 * 30
  206. apiDurationType = "monthly"
  207. }
  208. if durationHoursForRate < 1 {
  209. durationHoursForRate = 1
  210. }
  211. if apiDurationType == "" {
  212. apiDurationType = "hourly"
  213. }
  214. params := map[string]interface{}{
  215. "location_ids": req.LocationIDs,
  216. "hardware_id": req.HardwareID,
  217. "hardware_qty": hardwareQty,
  218. "gpus_per_container": req.GPUsPerContainer,
  219. "duration_type": apiDurationType,
  220. "duration_qty": durationQty,
  221. "duration_hours": req.DurationHours,
  222. "replica_count": req.ReplicaCount,
  223. "currency": currency,
  224. }
  225. endpoint := "/price" + buildQueryParams(params)
  226. resp, err := c.makeRequest("GET", endpoint, nil)
  227. if err != nil {
  228. return nil, fmt.Errorf("failed to get price estimation: %w", err)
  229. }
  230. // Parse according to the actual API response format from docs:
  231. // {
  232. // "data": {
  233. // "replica_count": 0,
  234. // "gpus_per_container": 0,
  235. // "available_replica_count": [0],
  236. // "discount": 0,
  237. // "ionet_fee": 0,
  238. // "ionet_fee_percent": 0,
  239. // "currency_conversion_fee": 0,
  240. // "currency_conversion_fee_percent": 0,
  241. // "total_cost_usdc": 0
  242. // }
  243. // }
  244. var pricingData struct {
  245. ReplicaCount int `json:"replica_count"`
  246. GPUsPerContainer int `json:"gpus_per_container"`
  247. AvailableReplicaCount []int `json:"available_replica_count"`
  248. Discount float64 `json:"discount"`
  249. IonetFee float64 `json:"ionet_fee"`
  250. IonetFeePercent float64 `json:"ionet_fee_percent"`
  251. CurrencyConversionFee float64 `json:"currency_conversion_fee"`
  252. CurrencyConversionFeePercent float64 `json:"currency_conversion_fee_percent"`
  253. TotalCostUSDC float64 `json:"total_cost_usdc"`
  254. }
  255. if err := decodeData(resp.Body, &pricingData); err != nil {
  256. return nil, fmt.Errorf("failed to parse price estimation response: %w", err)
  257. }
  258. // Convert to our internal format
  259. durationHoursFloat := float64(durationHoursForRate)
  260. if durationHoursFloat <= 0 {
  261. durationHoursFloat = 1
  262. }
  263. priceResp := &PriceEstimationResponse{
  264. EstimatedCost: pricingData.TotalCostUSDC,
  265. Currency: strings.ToUpper(currency),
  266. EstimationValid: true,
  267. PriceBreakdown: PriceBreakdown{
  268. ComputeCost: pricingData.TotalCostUSDC - pricingData.IonetFee - pricingData.CurrencyConversionFee,
  269. TotalCost: pricingData.TotalCostUSDC,
  270. HourlyRate: pricingData.TotalCostUSDC / durationHoursFloat,
  271. },
  272. }
  273. return priceResp, nil
  274. }
  275. // CheckClusterNameAvailability checks if a cluster name is available
  276. func (c *Client) CheckClusterNameAvailability(clusterName string) (bool, error) {
  277. if clusterName == "" {
  278. return false, fmt.Errorf("cluster name cannot be empty")
  279. }
  280. params := map[string]interface{}{
  281. "cluster_name": clusterName,
  282. }
  283. endpoint := "/clusters/check_cluster_name_availability" + buildQueryParams(params)
  284. resp, err := c.makeRequest("GET", endpoint, nil)
  285. if err != nil {
  286. return false, fmt.Errorf("failed to check cluster name availability: %w", err)
  287. }
  288. var availabilityResp bool
  289. if err := json.Unmarshal(resp.Body, &availabilityResp); err != nil {
  290. return false, fmt.Errorf("failed to parse cluster name availability response: %w", err)
  291. }
  292. return availabilityResp, nil
  293. }
  294. // UpdateClusterName updates the name of an existing cluster/deployment
  295. func (c *Client) UpdateClusterName(clusterID string, req *UpdateClusterNameRequest) (*UpdateClusterNameResponse, error) {
  296. if clusterID == "" {
  297. return nil, fmt.Errorf("cluster ID cannot be empty")
  298. }
  299. if req == nil {
  300. return nil, fmt.Errorf("update cluster name request cannot be nil")
  301. }
  302. if req.Name == "" {
  303. return nil, fmt.Errorf("cluster name cannot be empty")
  304. }
  305. endpoint := fmt.Sprintf("/clusters/%s/update-name", clusterID)
  306. resp, err := c.makeRequest("PUT", endpoint, req)
  307. if err != nil {
  308. return nil, fmt.Errorf("failed to update cluster name: %w", err)
  309. }
  310. // Parse the response directly without data wrapper based on API docs
  311. var updateResp UpdateClusterNameResponse
  312. if err := json.Unmarshal(resp.Body, &updateResp); err != nil {
  313. return nil, fmt.Errorf("failed to parse update cluster name response: %w", err)
  314. }
  315. return &updateResp, nil
  316. }