Skip to content

feat: Allow traefik merged dynamic configuration override with <project>.yaml - #6375

Closed
nickchomey wants to merge 31 commits into
ddev:masterfrom
nickchomey:20240703_nickchomey_traefik3
Closed

nickchomey wants to merge 31 commits into
ddev:masterfrom
nickchomey:20240703_nickchomey_traefik3

Conversation

@nickchomey

@nickchomey nickchomey commented Jul 4, 2024 •

Copy link
Copy Markdown
Collaborator

The Issue

Currently the only way to define any Traefik Middleware (or modify anything at all in the Traefik configs) is by removing #ddev-generated from the /pkg/ddevapp/traefik_config_template.yaml and ~/.ddev/traefik/static_config which, as described in #6357, invites all sorts of other issues. The solution is to make all #ddev-generated files extensible.

This was recently implemented for the static config via #6317. This PR is for the dynamic config

How This PR Solves The Issue

This PR adds a generalized merge mechanism to allow extra /project/.ddev/traefik/dynamic_config.*.yaml files to be merged into the <project>.yaml file, with the last alphanumeric file "winning". This can be used for adding middlewares as well as overriding any field in the dynamic config.

The dynamic_config.*.yaml files will also be able to contain {{go templates}} so that middlewares can dynamically use app variables to do things like rewrite app URLs in the response body (useful for Wordpress and Magento), or automatically "namespace" the middleware per active DDEV project.

Most users should never need to touch this - it would be best implemented via addons or other core code.

Manual Testing Instructions

  • create a ddev project with ddev config
  • copy/rename /project/traefik/dynamic_config.middleware.yaml.example to remove .example extension, which will use the fail2ban plugin
  • Likewise for ~/.ddev/traefik/static_config.plugins.yaml` to add fail2ban globally
  • ddev start
  • Check that routers and middleware are loading and working properly at http://localhost:10999/dashboard/#/
  • Do the same for a 2nd project and check the traefik dashboard to see that separate middleware has been created per router
  • Feel free to try defining other middlewares in both of those files, or changing the router assignments. Make sure to follow the same formatting, particularly with the {{ .App.Name }}- prefixes
  • Other fields in the dynamic config can be changed as well - e.g. tls:

Automated Testing Overview

A test has been added that injects a middleware definition via an extra config file.

Release/Deployment Notes

This should not affect anything else. It adds opt-in functionality, which would be best implemented via addons or other built-in mechanisms.

@nickchomey
nickchomey requested a review from a team as a code owner July 4, 2024 02:17
@github-actions github-actions Bot added the bugfix label Jul 4, 2024
@github-actions

github-actions Bot commented Jul 4, 2024 •

Copy link
Copy Markdown

Comment thread pkg/ddevapp/config.go Resolved
@rfay
rfay marked this pull request as draft July 4, 2024 19:05
@rfay

rfay commented Jul 4, 2024

Copy link
Copy Markdown
Member

Looks like the next hurdle is just TestCmdRestartJSON, https://buildkite.com/ddev/ddev-macos-arm64-mutagen/builds/8124#01907be5-07b3-4384-a0e9-aa1b1b01f567/15650-15654

failed to unmarshal logLine='Failed to read Extension YAML file. Probably doesn't exist: open /Users/testbot/tmp/ddevtest/TestCmdWordpress192791668/.ddev/traefik/.traefik-dynamic-config-extensions-template.yaml: no such file or directory'

Looks like a secondary failure, first the .traefik-dynamic-config-extensions-template.yaml doesn't exist, second the output of that causes the TestCmdRestartJSON to fail.

You can run tests manually really easily in vscode, just click the little arrowhead. Since this is a TestCmd test, make sure you have the correct built version of ddev in path.

@rfay
rfay marked this pull request as ready for review July 5, 2024 13:15
@rfay

rfay commented Jul 5, 2024

Copy link
Copy Markdown
Member

I don't understand why you didn't fill in the PR template here. Please update it to explain. (But thanks for the manual testing instructions!)

Please edit the OP with the required information:

## The Issue

Explain there why this PR is necessary,

`## How this PR solves the problem.

## Automated Testing Overview

@rfay rfay left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just beginning to look at this, but your comment about the creation of traefik-dynamic-config-extensions-template.yaml.example says:

I don't believe that existing projects will receive the /project/traefik/.traefik-dynamic-config-extensions-template.yaml.example file, as it is created with ddev config so that the file would be available prior to the first ddev start. Should that stay there, but also add some conditional logic to traefik.go to check for its existence, creating it if it doesn't exist?

This creation is being done in the wrong place. It should be processed configureTraefikForApp() in traefik.go, along with the other project-level traefik configuration.

Also, you're giving it an inappropriate name. .traefik_dynamic_config_extensions_template.yaml.example is a hidden file. We don't want an example to be hidden. I imagine it shouldn't have the name template in it either?

@rfay

rfay commented Jul 5, 2024

Copy link
Copy Markdown
Member

Please improve the testing instructions above. I took a look at the example file and it has all kinds of go templating in it.

{{ $webEnv := .App.WebEnvironment }}
middlewareAssignments:
  {{ .App.Name }}-web-80-http:
      - {{ .App.Name }}-redirectHttps
      - {{ .App.Name }}-my-fail2ban
  {{ .App.Name }}-web-80-https:
      - {{ .App.Name }}-my-fail2ban

Do we expect users to be able to do that? Or was the example file supposed to have been processed?

@rfay

rfay commented Jul 5, 2024

Copy link
Copy Markdown
Member

Your comments say

Finally, you can debug it by going to http://localhost:10999/dashboard/ and seeing if there were any errors for Routers or Middleware. You can click on any that are red to see the error message

Shouldn't ddev start have failed long before you can see router or middleware failures here?

@rfay rfay left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll take another look when I can understand the PR testing instructions and when Dockerfile stuff is removed and the example makes sense (I assume without go templating requirements?)

Comment thread pkg/ddevapp/config.go Resolved
@nickchomey

Copy link
Copy Markdown
Collaborator Author

I don't understand why you didn't fill in the PR template here. Please update it to explain. (But thanks for the manual testing instructions!)

Please edit the OP with the required information:

## The Issue

Explain there why this PR is necessary,

`## How this PR solves the problem.

## Automated Testing Overview

I believe when we created a PR to your PR together via zoom, I asked what to do about the template and you said just delete it. I'll create a new PR and copy the template from it to here and fill it out

@nickchomey

nickchomey commented Jul 5, 2024 •

Copy link
Copy Markdown
Collaborator Author

Just beginning to look at this, but your comment about the creation of traefik-dynamic-config-extensions-template.yaml.example says:

I don't believe that existing projects will receive the /project/traefik/.traefik-dynamic-config-extensions-template.yaml.example file, as it is created with ddev config so that the file would be available prior to the first ddev start. Should that stay there, but also add some conditional logic to traefik.go to check for its existence, creating it if it doesn't exist?

This creation is being done in the wrong place. It should be processed configureTraefikForApp() in traefik.go, along with the other project-level traefik configuration.

As I said in the comment that you quoted, I very much do think that this file should be created in config.go, so that it is there prior to any ddev start . But, again as I said, it could also be checked for in configureTraefikForApp() so that it could be created in existing projects.

Yet, I suppose very few other files are created prior to the first ddev start, which is fairly inconvenient (need to start, modify files, then restart - rather than the necessary files just being there to begin with), but that's the way it is...

So, sure I suppose I could just move the creation of this file from config.go to configureTraefikForApp() in order to stay consistent.

Also, you're giving it an inappropriate name. .traefik_dynamic_config_extensions_template.yaml.example is a hidden file. We don't want an example to be hidden. I imagine it shouldn't have the name template in it either?

I'm happy to rename it to whatever you like.

Please improve the testing instructions above.

Do you have any specific qualms and suggestions?

I took a look at the example file and it has all kinds of go templating in it.

{{ $webEnv := .App.WebEnvironment }}
middlewareAssignments:
{{ .App.Name }}-web-80-http:
- {{ .App.Name }}-redirectHttps
- {{ .App.Name }}-my-fail2ban
{{ .App.Name }}-web-80-https:
- {{ .App.Name }}-my-fail2ban
Do we expect users to be able to do that? Or was the example file supposed to have been processed?

It contains a template because it needs to be able to populate some app-specific things. Or at least that is the case for my redirect url stuff, which I showed you via zoom and we discussed

I could probably reconfigure it such that the App.Name stuff is prepended in Go, while maintaining the possibility for people to define templates in it. Yet, the status-quo to implement any middleware is to literally edit /pkg/ddevapp/traefik_config_template.yaml - a Go template file. So, I don't see much of a difference if they just need to now edit a different go template file.

Also, we've discussed a few times that this is something that very few people will or should ever touch - it would be better interacted with/populated by an addon or other core code. And if anyone does have the courage or competence to be messing with plugins, then I don't see it being particularly onerous for them to make sure to add App.Name where appropriate (especially when there's already an example and documentation).

I'm open to any specific suggestions though.

@nickchomey

nickchomey commented Jul 5, 2024 •

Copy link
Copy Markdown
Collaborator Author

Your comments say

Finally, you can debug it by going to http://localhost:10999/dashboard/ and seeing if there were any errors for Routers or Middleware. You can click on any that are red to see the error message

Shouldn't ddev start have failed long before you can see router or middleware failures here?

As far as I can tell, you simply have to wait for traefik to start up and try to load the middleware in order to find out if it was defined with proper yaml and plugin structure, no issues with url or other parameters, etc

Though, correct me if I'm wrong, but I don't think there's anything like that right now to validate the core traefik yaml - if you use wrong spacing, indents, hyphen etc everything will start up but the router will fail in some way.

The issue I had with v2 vs v3 syntax is a good example. I see no problem with this though - it fails, you can inspect why and then solve it. But, again, very few people should ever be touching any of this - and if they do, its at their own risk, as is documented throughout ddev

But if you know how to validate traefik yaml before loading traefik, I'd be happy to try to implement something - for both this PR and for traefik yaml more generally (both the static and dynamic config). But I dont see it as being feasible (or at least practical), or even necessary.

@rfay

rfay commented Jul 5, 2024

Copy link
Copy Markdown
Member

You don't have to create a new PR. Just edit the OP. Pull down the little editor in the upper right of the OP :)

@nickchomey

Copy link
Copy Markdown
Collaborator Author

You don't have to create a new PR. Just edit the OP. Pull down the little editor in the upper right of the OP :)

Yes, what I meant is I'll just start a new PR to get the template and copy it to here. I wouldn't actually submit (or even fill out) the new pr

@nickchomey
nickchomey force-pushed the 20240703_nickchomey_traefik3 branch 2 times, most recently from e344e44 to 35193d8 Compare July 6, 2024 22:11
@nickchomey
nickchomey requested a review from a team as a code owner July 6, 2024 22:11
@nickchomey
nickchomey marked this pull request as draft July 7, 2024 20:42
@nickchomey
nickchomey force-pushed the 20240703_nickchomey_traefik3 branch from 832b2ae to e7d6da4 Compare July 8, 2024 23:13
@nickchomey nickchomey changed the title fix: Traefik dynamic config middleware assignment feat: Allow traefik merged dynamic configuration override with <project>.yaml Jul 9, 2024
@nickchomey
nickchomey force-pushed the 20240703_nickchomey_traefik3 branch from 3d189cf to b1bd39b Compare July 12, 2024 20:10

@rfay rfay left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lots of comments, most super-easy. The part that isn't quite as easy is simplifying the flow of ConfigureTraefikForApp(). It does what it needs to do now, but it works a little too hard at it, resulting in too many lines of code and a harder flow. If I'm not mistaken, we can do the templating just once, and we can remove a number of if/else cases. I'll be happy to help with this if it's not obvious enough from the comments. I know you've already worked hard on this, you're almost to the finish line!

Comment thread pkg/ddevapp/traefik.go Resolved
Comment thread pkg/ddevapp/traefik.go Resolved
Comment thread pkg/ddevapp/traefik.go Resolved
Comment thread pkg/ddevapp/traefik.go Outdated
}

err = t.Execute(f, templateData)
err = t.Execute(dynamicConfigTemp, templateData)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need to do this whole templating stage do we, since we template the results of the merge?

@nickchomey nickchomey Jul 12, 2024 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it is necessary because, as I'm sure I explained before, we can't unmarshal traefik_config_template.yaml to merge it because it is full of templates (e.g. to define router names). So, no, it needs to be as it is - parse the template, merge it with the extra files, parse template again, write to the final file.

The only question, i suppose, is whether we parse it into a temp file or a map to avoid a temp file. Yet, as explained various times, if we are to use MergeYamlFiles, we need to generate a file. Moreover, the base config comes from traefik_config_template.yaml, which is in bundledAssets via go:embed, and it cannot be passed to that function. So we'd need an entirely different mergeyamlmapbundledassets function. Not at all worth it. It is more than fine as it is

On a related note, are the 7 nanoseconds of processing that we might have possibly been able to save here worth the many hours (or even days) of time we've spent on this? Let alone the social friction getting augered in on these minute details has caused...

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're already creating a temp file with the contents if I'm not mistaken.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's not valid yaml with the templates in it, then you're right. But how is that going to work below, where you have the same problem? All of the files would have to be preprocessed in that case.

@nickchomey nickchomey Jul 13, 2024 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The temp file gets its contents VIA the parsing of the template. If I just read the contents of the template into the temp file without parsing the template, then merging breaks because it cant unmarshal all of the templates in the string. (I actually have tried precisely this and it does, in fact, break).

As for the other files, yes, I initially preprocessed all of the templates precisely for this reason, prior to merging them all. But you insisted that i not do that anymore. So, it must be done like this and comes with the restriction (which i've moved from the docs to the readme) that you can't put a template at the start of a YAML key - it must be preceded by a character, or used in a value.

I could solve this problem by changing traefik_config_template.yaml to not use templates at the start of the lines

e.g. {{ .App.Name }}-web-80-http: is invalid, but web-80-http-{{ .App.Name }}: is valid.

Except the template is actually like this

{{ $appname }}-{{ $s.Service.InternalServiceName }}-{{ $s.Service.InternalServicePort }}-http:

So it would need to be

http-{{ $s.Service.InternalServiceName }}-{{ $s.Service.InternalServicePort }}-{{ $appname }}:

I actually would be quite happy to do that, precisely because it would make merging my rewriteurls middleware stuff considerably easier.

Yet, I suspect all the go template logic (if, range etc...) would break it still (or at least disappear). So, no point in trying

Perhaps we can just leave it all as is, and move on to far more important things?

"Premature optimization is the root of all evil"

Comment thread pkg/ddevapp/traefik.go Resolved
Comment thread pkg/ddevapp/traefik.go Resolved
@nickchomey

nickchomey commented Jul 13, 2024 •

Copy link
Copy Markdown
Collaborator Author

I have found a pretty meaningful bug/gotcha in this. If you have two files that set middlewares, the second one overwrites the router assignments of the first

e.g. you get this

test4-web-80-http:
  middlewares:
    - test4-relative-location-header
    - test4-relative-body-urls

instead of:

test4-web-80-http:
  middlewares:
    - test4-my-fail2ban
    - test4-redirectHttps
    - test4-relative-location-header
    - test4-relative-body-urls

I just tried running this without mergo.WithOverride (which we need in order to allow for overriding parameters) and, somewhat surprisingly, it doesn't actually fix this problem. It just literally prevents the override from happening, resulting in

test4-web-80-http:
  middlewares:
    - test4-my-fail2ban
    - test4-redirectHttps

The only reasonable solution I see, therefore, is to add documentation in the readme, example extra config file header, and website docs to the effect of "all middlewares must be defined in dynamic_config.middlewares.yaml.

It'll make it a bit trickier for my wordpress addon to add/merge what it needs into that single middlewares config (as opposed to just copying a config into the directory). But I dont see a reasonable way around this. So, I'll add the docs soon.

I'm also working through some ideas to improve things in other ways that I think will make everyone happier. I'll report back on that when ready

@rfay

rfay commented Jul 13, 2024

Copy link
Copy Markdown
Member

Could you please provide the example file that demonstrates this problem with middlewares assignments? Thanks! (I think you're saying that a second router of the same name overrides the middlewares assignments from the first one if they exist, and I'd expect that to be normal behavior)

… configs. Considerable refactoring of functions
@nickchomey

Copy link
Copy Markdown
Collaborator Author

Could you please provide the example file that demonstrates this problem with middlewares assignments? Thanks! (I think you're saying that a second router of the same name overrides the middlewares assignments from the first one if they exist, and I'd expect that to be normal behavior)

My wsl2 is in the process of crashing for reasons unknown - i'll sort it out. Anyway, i cant generate any files for you but it shouldnt be needed.

Just use the default dynamic_config.middlewares.yaml.example file (removing the example extension) and then make a copy of that and just change the names of the middlewares in both the middleware definition section as well as where they are assigned in the routers.

The definitions will merge just fine, but the assignments from the 2nd one will override the 1st.

@rfay

rfay commented Jul 13, 2024

Copy link
Copy Markdown
Member

The definitions will merge just fine, but the assignments from the 2nd one will override the 1st

Isn't that the intended behavior?

@nickchomey

Copy link
Copy Markdown
Collaborator Author

I just pushed a big commit that does the following:

  • restores the original functionality that I had implemented, where it first parses each config file for templates, then merges them all at the end. This solves the problem of not being able to include {{go templates }} in the yaml field/keys.
  • Refactored everything considerably into 5 or 6 new functions, leaving the core function quite clean, and hopefully everything more maintainable.

I timed how long the dynamic config merging and generations takes before and after this and both are in the realm of 1-2 milliseconds - so any qualms about extra processing are completely irrelevant, especially when the rest of ddev start is enormously redundant, and yet Docker is many orders of magnitude slower.

I'm sure you'll have suggestions for improvement - function and parameter names, where to put them, etc... But I REALLY hope you'll accept it. If not, I dont see any possibility for my continued involvement in this PR or ddev contributions altogether.

@nickchomey

nickchomey commented Jul 13, 2024 •

Copy link
Copy Markdown
Collaborator Author

The definitions will merge just fine, but the assignments from the 2nd one will override the 1st

Isn't that the intended behavior?

In some sense, perhaps. But lets say one config file defines and assigns fail2ban and another separate file defines and assigns redirectHttps (or anything else.

The definitions will both be merged as they are different names/text. BUt the assignments will not merge - only the last-to-be-touched middleware file will actually be assigned.

So, as described, you have to define all middlewares in one dynamic_config.middlewares.yaml file. Perhaps that's exactly what was planned/expected, but it wasn't clear in the docs etc... Or in my mind, for that matter - i figured different middlewares could be in different files. Its just the reality of the hyphens/data type - they're all treated as a single value with middlewares: as the key

Again, something liek this is only possible if you define and assign them all from one file.

test4-web-80-http:
  middlewares:
    - test4-my-fail2ban
    - test4-redirectHttps
    - test4-relative-location-header 
    - test4-relative-body-urls

If you separate any of those 4 middlewares into different files, they overwrite each other.

I forgot to update the docs/comments due to my refactoring work, but i'll do that when wsl2 comes back to life

@rfay

rfay commented Jul 13, 2024

Copy link
Copy Markdown
Member

I think what you're describing is the intended override behavior. In config.yaml we have two modes. The first (default) is merging, so config.yaml and config.*.yaml are all merged. Direct hits are overridden, but things like arrays (your case) are merged. For the explicit override case we have a special override_config directive, https://ddev.readthedocs.io/en/stable/users/configuration/config/#override_config, which makes it work as an explicit replacement instead of merge.

@nickchomey

Copy link
Copy Markdown
Collaborator Author

I think what you're describing is the intended override behavior. In config.yaml we have two modes. The first (default) is merging, so config.yaml and config.*.yaml are all merged. Direct hits are overridden, but things like arrays (your case) are merged. For the explicit override case we have a special override_config directive, https://ddev.readthedocs.io/en/stable/users/configuration/config/#override_config, which makes it work as an explicit replacement instead of merge.

That's fine. I'll just add some details so that people understand it better. If even I was mistaken about this, then others definitely would be.

@nickchomey

nickchomey commented Jul 14, 2024 •

Copy link
Copy Markdown
Collaborator Author

Looks like all tests are passing just fine with the big refactoring (except wsl2 and colima - they've failed a couple times without actually giving any useful information). I see no reason to believe that this is due to the code - must be the build machines.

It is working exceptionally well with the other stuff I'm working on (e.g. wordpress addon is seamlessly rewriting absolute urls to relative paths) - very helpful to have full go template capabilities available in the extra config files.

Please let me know what changes you'd like made, and I'll make them along with push some other minor edits that I've committed locally, and rebase from master.

@nickchomey
nickchomey requested a review from stasadev July 14, 2024 00:38
@rfay

rfay commented Jul 15, 2024

Copy link
Copy Markdown
Member

I have decided not to accept this PR, mostly because of the explicit threat. I wish you well on your journey, and am sorry that this was such a difficult process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants