|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package config |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "io" |
| 23 | + "net/http" |
| 24 | + |
| 25 | + "sigs.k8s.io/kwok/pkg/consts" |
| 26 | + "sigs.k8s.io/kwok/pkg/log" |
| 27 | + "sigs.k8s.io/kwok/pkg/utils/file" |
| 28 | + "sigs.k8s.io/kwok/pkg/utils/path" |
| 29 | +) |
| 30 | + |
| 31 | +// FetchDefaultConfig fetches the default configuration file from the remote URL |
| 32 | +// and saves it to the local file system if it doesn't already exist. |
| 33 | +func FetchDefaultConfig(ctx context.Context) error { |
| 34 | + fullPath := path.Join(WorkDir, consts.ConfigName) |
| 35 | + if file.Exists(fullPath) { |
| 36 | + return nil |
| 37 | + } |
| 38 | + |
| 39 | + logger := log.FromContext(ctx) |
| 40 | + |
| 41 | + logger.Info("Fetch default config from remote", |
| 42 | + "url", consts.KwokctlDefaultConfigURL, |
| 43 | + "path", path.RelFromHome(fullPath), |
| 44 | + ) |
| 45 | + |
| 46 | + err := file.MkdirAll(WorkDir) |
| 47 | + if err != nil { |
| 48 | + return err |
| 49 | + } |
| 50 | + |
| 51 | + f, err := file.Open(fullPath) |
| 52 | + if err != nil { |
| 53 | + return err |
| 54 | + } |
| 55 | + defer func() { |
| 56 | + _ = f.Close() |
| 57 | + }() |
| 58 | + |
| 59 | + resp, err := http.Get(consts.KwokctlDefaultConfigURL) |
| 60 | + if err != nil { |
| 61 | + return err |
| 62 | + } |
| 63 | + defer func() { |
| 64 | + _ = resp.Body.Close() |
| 65 | + }() |
| 66 | + |
| 67 | + if resp.StatusCode != http.StatusOK { |
| 68 | + return fmt.Errorf("status code %d", resp.StatusCode) |
| 69 | + } |
| 70 | + |
| 71 | + _, err = io.Copy(f, resp.Body) |
| 72 | + if err != nil { |
| 73 | + return err |
| 74 | + } |
| 75 | + return nil |
| 76 | +} |
0 commit comments