| 70 | } |
| 71 | |
| 72 | func (m *mapper) MapRules(user string, ruleConfigs map[string][]rulefmt.RuleGroup) (bool, []string, error) { |
| 73 | anyUpdated := false |
| 74 | filenames := []string{} |
| 75 | |
| 76 | // user rule files will be stored as `/<path>/<userid>/<encoded filename>` |
| 77 | path := filepath.Join(m.Path, user) |
| 78 | err := m.FS.MkdirAll(path, 0777) |
| 79 | if err != nil { |
| 80 | return false, nil, err |
| 81 | } |
| 82 | |
| 83 | // write all rule configs to disk |
| 84 | for filename, groups := range ruleConfigs { |
| 85 | // Store the encoded file name to better handle `/` characters |
| 86 | encodedFileName := url.PathEscape(filename) |
| 87 | fullFileName := filepath.Join(path, encodedFileName) |
| 88 | |
| 89 | fileUpdated, err := m.writeRuleGroupsIfNewer(groups, fullFileName) |
| 90 | if err != nil { |
| 91 | return false, nil, err |
| 92 | } |
| 93 | filenames = append(filenames, fullFileName) |
| 94 | anyUpdated = anyUpdated || fileUpdated |
| 95 | } |
| 96 | |
| 97 | // and clean any up that shouldn't exist |
| 98 | existingFiles, err := afero.ReadDir(m.FS, path) |
| 99 | if err != nil { |
| 100 | return false, nil, err |
| 101 | } |
| 102 | |
| 103 | for _, existingFile := range existingFiles { |
| 104 | fullFileName := filepath.Join(path, existingFile.Name()) |
| 105 | |
| 106 | // Ensure the namespace is decoded from a url path encoding to see if it is still required |
| 107 | decodedNamespace, err := url.PathUnescape(existingFile.Name()) |
| 108 | if err != nil { |
| 109 | level.Warn(m.logger).Log("msg", "unable to remove rule file on disk", "file", fullFileName, "err", err) |
| 110 | continue |
| 111 | } |
| 112 | |
| 113 | ruleGroups := ruleConfigs[string(decodedNamespace)] |
| 114 | |
| 115 | if ruleGroups == nil { |
| 116 | err = m.FS.Remove(fullFileName) |
| 117 | if err != nil { |
| 118 | level.Warn(m.logger).Log("msg", "unable to remove rule file on disk", "file", fullFileName, "err", err) |
| 119 | } |
| 120 | anyUpdated = true |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | return anyUpdated, filenames, nil |
| 125 | } |
| 126 | |
| 127 | func (m *mapper) writeRuleGroupsIfNewer(groups []rulefmt.RuleGroup, filename string) (bool, error) { |
| 128 | sort.Slice(groups, func(i, j int) bool { |