Skip to content

Commit 32d569c

Browse files
authored
Merge pull request #3509 from yyy1000/grafana-plugin-2
✨ Add Grafana Plugin migration in alpha generate subcommand -- Step 2
2 parents c811b20 + 7c1ca0d commit 32d569c

File tree

4 files changed

+65
-22
lines changed

4 files changed

+65
-22
lines changed

go.mod

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ require (
2323
github.com/inconshreveable/mousetrap v1.1.0 // indirect
2424
github.com/kr/text v0.2.0 // indirect
2525
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
26-
golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1
2726
golang.org/x/mod v0.12.0 // indirect
2827
golang.org/x/net v0.12.0 // indirect
2928
golang.org/x/sys v0.10.0 // indirect

go.sum

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,6 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
199199
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
200200
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
201201
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
202-
golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw=
203-
golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
204202
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
205203
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
206204
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=

pkg/rescaffold/migrate.go

Lines changed: 42 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@ import (
2121
"os/exec"
2222
"strings"
2323

24-
"golang.org/x/exp/slices"
25-
2624
"github.com/spf13/afero"
2725
"sigs.k8s.io/kubebuilder/v3/pkg/config"
2826
"sigs.k8s.io/kubebuilder/v3/pkg/config/store"
@@ -42,7 +40,7 @@ const grafanaPluginKey = "grafana.kubebuilder.io/v1-alpha"
4240

4341
func (opts *MigrateOptions) Rescaffold() error {
4442
config := yaml.New(machinery.Filesystem{FS: afero.NewOsFs()})
45-
if err := config.LoadFrom(opts.InputDir); err != nil {
43+
if err := config.LoadFrom(fmt.Sprintf("%s/%s", opts.InputDir, yaml.DefaultPath)); err != nil {
4644
log.Fatalf("Failed to load PROJECT file %v", err)
4745
}
4846
// create output directory
@@ -67,7 +65,7 @@ func (opts *MigrateOptions) Rescaffold() error {
6765
log.Fatalf("Failed to run create API subcommand %v", err)
6866
}
6967
// plugin specific migration
70-
if err := kubebuilderGrafanaPlugin(config); err != nil {
68+
if err := migrateGrafanaPlugin(config, opts.InputDir, opts.OutputDir); err != nil {
7169
log.Fatalf("Failed to run plugin migration %v", err)
7270
}
7371
return nil
@@ -102,7 +100,7 @@ func getInputPath(currentWorkingDirectory string, inputPath string) (string, err
102100
if _, err := os.Stat(projectPath); os.IsNotExist(err) {
103101
return "", fmt.Errorf("PROJECT path: %s does not exist. %v", projectPath, err)
104102
}
105-
return projectPath, nil
103+
return inputPath, nil
106104
}
107105

108106
func getOutputPath(currentWorkingDirectory, outputPath string) (string, error) {
@@ -152,24 +150,26 @@ func kubebuilderCreate(store store.Store) error {
152150
return nil
153151
}
154152

155-
func kubebuilderGrafanaPlugin(store store.Store) error {
156-
// If the plugin is already in the plugin chain, we don't need call 'edit' method
157-
// Because the plugin is already migrated in the previous step
158-
plugins := store.Config().GetPluginChain()
159-
if slices.Contains(plugins, grafanaPluginKey) {
160-
return nil
161-
}
162-
// If the plugin is not in the plugin chain, we need to call 'edit' method to add the plugin
153+
func migrateGrafanaPlugin(store store.Store, src, des string) error {
163154
var grafanaPlugin struct{}
164155
err := store.Config().DecodePluginConfig(grafanaPluginKey, grafanaPlugin)
165156
// If the grafana plugin is not found, we don't need to migrate
166-
if errors.As(err, &config.PluginKeyNotFoundError{}) {
167-
return nil
157+
if err != nil {
158+
if errors.As(err, &config.PluginKeyNotFoundError{}) {
159+
log.Printf("Grafana plugin is not found, skip the migration")
160+
return nil
161+
}
162+
return fmt.Errorf("failed to decode grafana plugin config %v", err)
168163
}
164+
err = kubebuilderGrafanaEdit()
169165
if err != nil {
170-
return fmt.Errorf("Failed to Decode Grafana Plugin: %s. %v", grafanaPluginKey, err)
166+
return err
167+
}
168+
err = grafanaConfigMigrate(src, des)
169+
if err != nil {
170+
return err
171171
}
172-
return migrateGrafanaPlugin()
172+
return kubebuilderGrafanaEdit()
173173
}
174174

175175
func getInitArgs(store store.Store) []string {
@@ -258,7 +258,30 @@ func getWebhookResourceFlags(resource resource.Resource) []string {
258258
return args
259259
}
260260

261-
func migrateGrafanaPlugin() error {
261+
func copyFile(src, des string) error {
262+
// nolint:gosec
263+
bytesRead, err := os.ReadFile(src)
264+
if err != nil {
265+
return fmt.Errorf("Source file path: %s does not exist. %v", src, err)
266+
}
267+
//Copy all the contents to the desitination file
268+
// nolint:gosec
269+
return os.WriteFile(des, bytesRead, 0755)
270+
}
271+
272+
func grafanaConfigMigrate(src, des string) error {
273+
grafanaConfig := fmt.Sprintf("%s/%s", src, "grafana/custom-metrics/config.yaml")
274+
if _, err := os.Stat(grafanaConfig); os.IsNotExist(err) {
275+
return fmt.Errorf("Grafana Config path: %s does not exist. %v", grafanaConfig, err)
276+
}
277+
return copyFile(grafanaConfig, fmt.Sprintf("%s/%s", des, "grafana/custom-metrics/config.yaml"))
278+
}
279+
280+
func kubebuilderGrafanaEdit() error {
262281
args := []string{"edit", "--plugins", grafanaPluginKey}
263-
return util.RunCmd("kubebuilder edit", "kubebuilder", args...)
282+
err := util.RunCmd("kubebuilder edit", "kubebuilder", args...)
283+
if err != nil {
284+
return fmt.Errorf("Failed to run edit subcommand for Grafana Plugin %v", err)
285+
}
286+
return nil
264287
}

test/e2e/alphagenerate/generate_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ package alphagenerate
1818

1919
import (
2020
"fmt"
21+
"io"
22+
"os"
2123
"path/filepath"
2224

2325
pluginutil "sigs.k8s.io/kubebuilder/v3/pkg/plugin/util"
@@ -127,6 +129,16 @@ func ReGenerateProject(kbc *utils.TestContext) {
127129
)
128130
ExpectWithOffset(1, err).NotTo(HaveOccurred())
129131

132+
By("Edit the grafana config file")
133+
grafanaConfig, err := os.OpenFile(filepath.Join(kbc.Dir, "grafana/custom-metrics/config.yaml"),
134+
os.O_APPEND|os.O_WRONLY, 0644)
135+
ExpectWithOffset(1, err).NotTo(HaveOccurred())
136+
newLine := "test_new_line"
137+
_, err = io.WriteString(grafanaConfig, newLine)
138+
ExpectWithOffset(1, err).NotTo(HaveOccurred())
139+
err = grafanaConfig.Close()
140+
ExpectWithOffset(1, err).NotTo(HaveOccurred())
141+
130142
By("regenerating the project at another output directory")
131143
err = kbc.Regenerate(
132144
"--input-dir", kbc.Dir,
@@ -191,4 +203,15 @@ func ReGenerateProject(kbc *utils.TestContext) {
191203
filepath.Join(kbc.Dir, "testdir2", "PROJECT"), grafanaPlugin)
192204
ExpectWithOffset(1, err).NotTo(HaveOccurred())
193205
ExpectWithOffset(1, fileContainsExpr).To(BeTrue())
206+
207+
By("checking if the generated grafana config file has the same content as the old one")
208+
grafanaConfigPath := filepath.Join(kbc.Dir, "grafana/custom-metrics/config.yaml")
209+
generatedGrafanaConfigPath := filepath.Join(kbc.Dir, "testdir2", "grafana/custom-metrics/config.yaml")
210+
Expect(grafanaConfigPath).Should(BeARegularFile())
211+
Expect(generatedGrafanaConfigPath).Should(BeARegularFile())
212+
bytesBefore, err := os.ReadFile(grafanaConfigPath)
213+
Expect(err).NotTo(HaveOccurred())
214+
bytesAfter, err := os.ReadFile(generatedGrafanaConfigPath)
215+
Expect(err).NotTo(HaveOccurred())
216+
Expect(bytesBefore).Should(Equal(bytesAfter))
194217
}

0 commit comments

Comments
 (0)