You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.4 KiB

  1. // Copyright (c) 2014 Couchbase, Inc.
  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 bleve
  15. import (
  16. "encoding/json"
  17. "io/ioutil"
  18. "os"
  19. "github.com/blevesearch/bleve/index/upsidedown"
  20. )
  21. const metaFilename = "index_meta.json"
  22. type indexMeta struct {
  23. Storage string `json:"storage"`
  24. IndexType string `json:"index_type"`
  25. Config map[string]interface{} `json:"config,omitempty"`
  26. }
  27. func newIndexMeta(indexType string, storage string, config map[string]interface{}) *indexMeta {
  28. return &indexMeta{
  29. IndexType: indexType,
  30. Storage: storage,
  31. Config: config,
  32. }
  33. }
  34. func openIndexMeta(path string) (*indexMeta, error) {
  35. if _, err := os.Stat(path); os.IsNotExist(err) {
  36. return nil, ErrorIndexPathDoesNotExist
  37. }
  38. indexMetaPath := indexMetaPath(path)
  39. metaBytes, err := ioutil.ReadFile(indexMetaPath)
  40. if err != nil {
  41. return nil, ErrorIndexMetaMissing
  42. }
  43. var im indexMeta
  44. err = json.Unmarshal(metaBytes, &im)
  45. if err != nil {
  46. return nil, ErrorIndexMetaCorrupt
  47. }
  48. if im.IndexType == "" {
  49. im.IndexType = upsidedown.Name
  50. }
  51. return &im, nil
  52. }
  53. func (i *indexMeta) Save(path string) (err error) {
  54. indexMetaPath := indexMetaPath(path)
  55. // ensure any necessary parent directories exist
  56. err = os.MkdirAll(path, 0700)
  57. if err != nil {
  58. if os.IsExist(err) {
  59. return ErrorIndexPathExists
  60. }
  61. return err
  62. }
  63. metaBytes, err := json.Marshal(i)
  64. if err != nil {
  65. return err
  66. }
  67. indexMetaFile, err := os.OpenFile(indexMetaPath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
  68. if err != nil {
  69. if os.IsExist(err) {
  70. return ErrorIndexPathExists
  71. }
  72. return err
  73. }
  74. defer func() {
  75. if ierr := indexMetaFile.Close(); err == nil && ierr != nil {
  76. err = ierr
  77. }
  78. }()
  79. _, err = indexMetaFile.Write(metaBytes)
  80. if err != nil {
  81. return err
  82. }
  83. return nil
  84. }
  85. func indexMetaPath(path string) string {
  86. return path + string(os.PathSeparator) + metaFilename
  87. }