本站源代码
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.

98 lines
2.4KB

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