github.com/sacloud/libsacloud/v2@v2.32.3/helper/service/ipaddress/update_host_name_service.go (about) 1 // Copyright 2016-2022 The Libsacloud Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package ipaddress 16 17 import ( 18 "context" 19 "fmt" 20 "time" 21 22 "github.com/sacloud/libsacloud/v2/sacloud" 23 ) 24 25 const ( 26 defaultRetryMax = 30 27 defaultRetryInterval = 10 28 ) 29 30 func (s *Service) UpdateHostName(req *UpdateHostNameRequest) error { 31 return s.UpdateHostNameWithContext(context.Background(), req) 32 } 33 34 func (s *Service) UpdateHostNameWithContext(ctx context.Context, req *UpdateHostNameRequest) error { 35 if err := req.Validate(); err != nil { 36 return err 37 } 38 39 client := sacloud.NewIPAddressOp(s.caller) 40 _, err := client.Read(ctx, req.Zone, req.IPAddress) 41 if err != nil { 42 return err 43 } 44 45 if req.RetryMax == 0 { 46 req.RetryMax = defaultRetryMax 47 } 48 if req.RetryInterval == 0 { 49 req.RetryInterval = defaultRetryInterval 50 } 51 52 i := 0 53 success := false 54 for i < req.RetryMax { 55 if err := ctx.Err(); err != nil { 56 return fmt.Errorf("updating the HostName for %s failed: %s", req.IPAddress, err) 57 } 58 if _, err = client.UpdateHostName(ctx, req.Zone, req.IPAddress, req.HostName); err == nil { 59 success = true 60 break 61 } 62 time.Sleep(time.Duration(req.RetryInterval) * time.Second) 63 i++ 64 } 65 66 if !success { 67 return fmt.Errorf("updating the HostName for %s failed: giving up on setting the HostName: max attempts exceeded", req.IPAddress) 68 } 69 return nil 70 }