reverse.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2019 Yunion
  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. package dns
  15. import (
  16. "context"
  17. "strings"
  18. "github.com/coredns/coredns/plugin"
  19. "github.com/coredns/coredns/plugin/etcd/msg"
  20. "github.com/coredns/coredns/plugin/pkg/dnsutil"
  21. "github.com/coredns/coredns/request"
  22. "yunion.io/x/onecloud/pkg/compute/models"
  23. )
  24. // Reverse implements the ServiceBackend interface
  25. func (r *SRegionDNS) Reverse(ctx context.Context, state request.Request, exact bool, opt plugin.Options) (services []msg.Service, err error) {
  26. ip := dnsutil.ExtractAddressFromReverse(state.Name())
  27. if ip == "" {
  28. _, e := r.Records(ctx, state, exact)
  29. return nil, e
  30. }
  31. records, err := r.getNameForIp(ip, state)
  32. return records, err
  33. }
  34. func (r *SRegionDNS) getNameForIp(ip string, state request.Request) ([]msg.Service, error) {
  35. req := parseRequest(state)
  36. // 1. try local dns records table
  37. recs, _ := models.DnsRecordManager.QueryPtr(req.ProjectId(), ip)
  38. if len(recs) > 0 {
  39. services := make([]msg.Service, 0, len(recs))
  40. for _, rec := range recs {
  41. services = append(services, msg.Service{Host: rec.DnsName, TTL: uint32(rec.TTL)})
  42. }
  43. return services, nil
  44. }
  45. // 2. try guests table
  46. guest := models.GuestnetworkManager.GetGuestByAddress(ip, req.ProjectId())
  47. if guest != nil {
  48. return []msg.Service{{Host: r.joinDomain(guest.Hostname), TTL: defaultTTL}}, nil
  49. }
  50. // 3. try hosts table
  51. host := models.HostnetworkManager.GetHostByAddress(ip)
  52. if host != nil {
  53. return []msg.Service{{Host: r.joinDomain(host.Name), TTL: defaultTTL}}, nil
  54. }
  55. return nil, errNotFound
  56. }
  57. func (r *SRegionDNS) joinDomain(name string) string {
  58. return strings.Join([]string{name, r.PrimaryZone}, ".")
  59. }