Browse Source

Revamp version stuff Yet Again, make the AmbScout class function, and let the CLI use it.

Flynn 1 year ago
parent
commit
66c1c54f0e

+ 37
- 15
VERSION-template.py View File

@@ -12,11 +12,32 @@
12 12
 # See the License for the specific language governing permissions and
13 13
 # limitations under the License
14 14
 
15
+from typing import NamedTuple
16
+
17
+
18
+class GitInfo(NamedTuple):
19
+    commit: str
20
+    branch: str
21
+    dirty: bool
22
+    description: str
23
+
24
+
25
+class BuildInfo(NamedTuple):
26
+    version: str
27
+    git: GitInfo
28
+
29
+
15 30
 Version = "{{VERSION}}"
16
-GitDescription = "{{GITDESCRIPTION}}"
17
-GitBranch = "{{GITBRANCH}}"
18
-GitCommit = "{{GITCOMMIT}}"
19
-GitDirty = bool("{{GITDIRTY}}")
31
+
32
+Build = BuildInfo(
33
+    version=Version,
34
+    git=GitInfo(
35
+        commit="{{GITCOMMIT}}",
36
+        branch="{{GITBRANCH}}",
37
+        dirty=bool("{{GITDIRTY}}"),
38
+        description="{{GITDESCRIPTION}}",
39
+    )
40
+)
20 41
 
21 42
 if __name__ == "__main__":
22 43
     import sys
@@ -29,19 +50,20 @@ if __name__ == "__main__":
29 50
     if (cmd == '--version') or (cmd == '-V'):
30 51
         print(Version)
31 52
     elif cmd == '--desc':
32
-        print(GitDescription)
53
+        print(Build.git.description)
33 54
     elif cmd == '--branch':
34
-        print(GitBranch)
55
+        print(Build.git.branch)
35 56
     elif cmd == '--commit':
36
-        print(GitCommit)
57
+        print(Build.git.commit)
37 58
     elif cmd == '--dirty':
38
-        print(GitDirty)
59
+        print(Build.git.dirty)
39 60
     elif cmd == '--all':
40
-        print("Version:        %s" % Version)
41
-        print("GitBranch:      %s" % GitBranch)
42
-        print("GitCommit:      %s" % GitCommit)
43
-        print("GitDirty:       %s" % GitDirty)
44
-        print("GitDescription: %s" % GitDescription)
45
-    else: # compact
61
+        print("version:         %s" % Version)
62
+        print("git.branch:      %s" % Build.git.branch)
63
+        print("git.commit:      %s" % Build.git.commit)
64
+        print("git.dirty:       %s" % Build.git.dirty)
65
+        print("git.description: %s" % Build.git.description)
66
+    else:   # compact
46 67
         print("%s (%s at %s on %s%s)" %
47
-              (Version, GitDescription, GitCommit, GitBranch, " - dirty" if GitDirty else ""))
68
+              (Version, Build.git.description, Build.git.commit, Build.git.branch,
69
+               " - dirty" if Build.git.dirty else ""))

+ 2
- 1
ambassador/ambassador/__init__.py View File

@@ -14,6 +14,7 @@
14 14
 
15 15
 from .config import Config
16 16
 from .ir import IR
17
-from .ambscout import AmbScout as Scout
17
+from .ambscout import AmbScout as Scout, ScoutNotice
18 18
 from .diagnostics import Diagnostics
19 19
 from .envoy import EnvoyConfig
20
+from .VERSION import Version, Build, BuildInfo

+ 267
- 161
ambassador/ambassador/ambscout.py View File

@@ -1,173 +1,279 @@
1
+from typing import ClassVar, Dict, List, Optional, Tuple, Union
2
+
3
+import datetime
4
+import json
5
+import logging
6
+import re
1 7
 import os
2 8
 
9
+import semantic_version
10
+
3 11
 from scout import Scout
4 12
 
13
+# Import version stuff directly from ambassador.VERSION to avoid a circular import.
14
+from .VERSION import Version, Build, BuildInfo
15
+
16
+ScoutNotice = Union[str, Dict[str, str]]
17
+
18
+
5 19
 class AmbScout:
20
+    reTaggedBranch: ClassVar = re.compile(r'^(\d+\.\d+\.\d+)(-[a-zA-Z][a-zA-Z]\d+)?$')
21
+    reGitDescription: ClassVar = re.compile(r'-(\d+)-g([0-9a-f]+)$')
22
+
23
+    install_id: str
24
+    runtime: str
25
+    namespace: str
26
+
27
+    version: str
28
+    semver: Optional[semantic_version.Version]
29
+
30
+    _scout: Optional[Scout]
31
+    _scout_error: Optional[str]
32
+
33
+    _notices: Optional[List[ScoutNotice]]
34
+    _last_result: Optional[dict]
35
+    _last_update: Optional[datetime.datetime]
36
+    _update_frequency: Optional[datetime.timedelta]
37
+
38
+    _latest_version: Optional[str] = None
39
+    _latest_semver: Optional[semantic_version.Version] = None
40
+
6 41
     def __init__(self) -> None:
7
-        scout_install_id = os.environ.get('AMBASSADOR_SCOUT_ID', "00000000-0000-0000-0000-000000000000")
42
+        self.install_id = os.environ.get('AMBASSADOR_SCOUT_ID', "00000000-0000-0000-0000-000000000000")
43
+        self.runtime = "kubernetes" if os.environ.get('KUBERNETES_SERVICE_HOST', None) else "docker"
44
+        self.namespace = os.environ.get('AMBASSADOR_NAMESPACE', 'default')
8 45
 
9
-        try:
10
-            self._scout = Scout(app="ambassador", version="0.0.1-crap", install_id=scout_install_id)
11
-            self._scout_error = None
12
-        except OSError as e:
13
-            self._scout_error = e
46
+        self.version = self.parse_git_description(Version, Build)
47
+        self.semver = self.get_semver(self.version)
48
+
49
+        self.logger = logging.getLogger("ambassador.scout")
50
+        self.logger.setLevel(logging.DEBUG)
51
+
52
+        self.logger.debug("Ambassador version %s" % Version)
53
+        self.logger.debug("Scout version      %s%s" % (self.version, " - BAD SEMVER" if not self.semver else ""))
54
+        self.logger.debug("Runtime            %s" % self.runtime)
55
+        self.logger.debug("Namespace          %s" % self.namespace)
56
+
57
+        self._scout = None
58
+        self._scout_error = None
59
+
60
+        self._notices = None
61
+        self._last_result = None
62
+        self._last_update = datetime.datetime.now() - datetime.timedelta(hours=24)
63
+        self._update_frequency = datetime.timedelta(hours=4)
64
+        self._latest_version = None
65
+        self._latest_semver = None
14 66
 
15 67
     def __str__(self) -> str:
16 68
         return ("%s: %s" % ("OK" if self._scout else "??", 
17 69
                             self._scout_error if self._scout_error else "OK"))
18 70
 
19
-# def get_semver(what, version_string):
20
-#     semver = None
21
-
22
-#     try:
23
-#         semver = semantic_version.Version(version_string)
24
-#     except ValueError:
25
-#         pass
26
-
27
-#     return semver
28
-
29
-#     # Weird stuff. The build version looks like
30
-#     #
31
-#     # 0.12.0                    for a prod build, or
32
-#     # 0.12.1-b2.da5d895.DIRTY   for a dev build (in this case made from a dirty true)
33
-#     #
34
-#     # Now:
35
-#     # - Scout needs a build number (semver "+something") to flag a non-prod release;
36
-#     #   but
37
-#     # - DockerHub cannot use a build number at all; but
38
-#     # - 0.12.1-b2 comes _before_ 0.12.1+b2 in SemVer land.
39
-#     #
40
-#     # FFS.
41
-#     #
42
-#     # We cope with this by transforming e.g.
43
-#     #
44
-#     # 0.12.1-b2.da5d895.DIRTY into 0.12.1-b2+da5d895.DIRTY
45
-#     #
46
-#     # for Scout.
47
-
48
-#     scout_version = Version
49
-
50
-#     if '-' in scout_version:
51
-#         # TODO(plombardi): This version code needs to be rewritten. We should only report RC and GA versions.
52
-#         #
53
-#         # As of the time when we moved to streamlined branch, merge and release model the way versions in development
54
-#         # land are rendered has changed. A development version no longer has any <MAJOR>.<MINOR>.<PATCH> information and
55
-#         # is instead rendered as <BRANCH_NAME>-<GIT_SHORT_HASH>[-dirty] where [-dirty] is only appended for modified
56
-#         # source trees.
57
-#         #
58
-#         # Long term we are planning to remove the version report for development branches anyways so all of this
59
-#         # formatting for versions
60
-
61
-#         scout_version = "0.0.0-" + Version.split("-")[1]  # middle part is commit hash
62
-#         # Dev build!
63
-#         # v, p = scout_version.split('-')
64
-#         # p, b = p.split('.', 1) if ('.' in p) else (0, p)
65
-#         #
66
-#         # scout_version = "%s-%s+%s" % (v, p, b)
67
-
68
-#     # Use scout_version here, not __version__, because the version
69
-#     # coming back from Scout will use build numbers for dev builds, but
70
-#     # __version__ won't, and we need to be consistent for comparison.
71
-#     current_semver = get_semver("current", scout_version)
72
-
73
-# Moved to config.py
74
-##     # When using multiple Ambassadors in one cluster, use AMBASSADOR_ID to distinguish them.
75
-##     ambassador_id = os.environ.get('AMBASSADOR_ID', 'default')
76
-
77
-##     runtime = "kubernetes" if os.environ.get('KUBERNETES_SERVICE_HOST', None) else "docker"
78
-##     namespace = os.environ.get('AMBASSADOR_NAMESPACE', 'default')
79
-
80
-#     # Default to using the Nil UUID unless the environment variable is set explicitly
81
-#     scout_install_id = os.environ.get('AMBASSADOR_SCOUT_ID', "00000000-0000-0000-0000-000000000000")
82
-
83
-#     try:
84
-#         scout = Scout(app="ambassador", version=scout_version, install_id=scout_install_id)
85
-#         scout_error = None
86
-#     except OSError as e:
87
-#         scout_error = e
88
-
89
-#     scout_latest_version = None
90
-#     scout_latest_semver = None
91
-#     scout_notices = []
92
-
93
-#     scout_last_response = None
94
-#     scout_last_update = datetime.datetime.now() - datetime.timedelta(hours=24)
95
-#     scout_update_frequency = datetime.timedelta(hours=4)
96
-
97
-#     @classmethod
98
-#     def scout_report(klass, force_result=None, **kwargs):
99
-#         _notices = []
100
-
101
-#         env_result = os.environ.get("AMBASSADOR_SCOUT_RESULT", None)
102
-#         if env_result:
103
-#             force_result = json.loads(env_result)
104
-
105
-#         result = force_result
106
-#         result_timestamp = None
107
-#         result_was_cached = False
108
-
109
-#         if not result:
110
-#             if Config.scout:
111
-#                 if 'runtime' not in kwargs:
112
-#                     kwargs['runtime'] = Config.runtime
113
-
114
-#                 # How long since the last Scout update? If it's been more than an hour,
115
-#                 # check Scout again.
116
-
117
-#                 now = datetime.datetime.now()
118
-
119
-#                 if (now - Config.scout_last_update) > Config.scout_update_frequency:
120
-#                     result = Config.scout.report(**kwargs)
121
-
122
-#                     Config.scout_last_update = now
123
-#                     Config.scout_last_result = dict(**result)
124
-#                 else:
125
-#                     # _notices.append({ "level": "debug", "message": "Returning cached result" })
126
-#                     result = dict(**Config.scout_last_result)
127
-#                     result_was_cached = True
128
-
129
-#                 result_timestamp = Config.scout_last_update
130
-#             else:
131
-#                 result = { "scout": "unavailable" }
132
-#                 result_timestamp = datetime.datetime.now()
133
-#         else:
134
-#             _notices.append({ "level": "debug", "message": "Returning forced result" })
135
-#             result_timestamp = datetime.datetime.now()
136
-
137
-#         if not Config.current_semver:
138
-#             _notices.append({
139
-#                 "level": "warning",
140
-#                 "message": "Ambassador has bad version '%s'??!" % Config.scout_version
141
-#             })
142
-
143
-#         result['cached'] = result_was_cached
144
-#         result['timestamp'] = result_timestamp.timestamp()
145
-
146
-#         # Do version & notices stuff.
147
-#         if 'latest_version' in result:
148
-#             latest_version = result['latest_version']
149
-#             latest_semver = get_semver("latest", latest_version)
150
-
151
-#             if latest_semver:
152
-#                 Config.scout_latest_version = latest_version
153
-#                 Config.scout_latest_semver = latest_semver
154
-#             else:
155
-#                 _notices.append({
156
-#                     "level": "warning",
157
-#                     "message": "Scout returned bad version '%s'??!" % latest_version
158
-#                 })
159
-
160
-#         if (Config.scout_latest_semver and
161
-#             ((not Config.current_semver) or
162
-#              (Config.scout_latest_semver > Config.current_semver))):
163
-#             _notices.append({
164
-#                 "level": "info",
165
-#                 "message": "Upgrade available! to Ambassador version %s" % Config.scout_latest_semver
166
-#             })
167
-
168
-#         if 'notices' in result:
169
-#             _notices.extend(result['notices'])
170
-
171
-#         Config.scout_notices = _notices
172
-
173
-#         return result
71
+    @property
72
+    def scout(self) -> Optional[Scout]:
73
+        if not self._scout:
74
+            try:
75
+                self._scout = Scout(app="ambassador", version=self.version, install_id=self.install_id)
76
+                self._scout_error = None
77
+                self.logger.debug("Scout connection established")
78
+            except OSError as e:
79
+                self._scout = None
80
+                self._scout_error = e
81
+                self.logger.debug("Scout connection failed, will retry later: %s" % self._scout_error)
82
+
83
+        return self._scout
84
+
85
+    def report(self, force_result: Optional[dict]=None, **kwargs) -> Tuple[dict, List[ScoutNotice]]:
86
+        _notices: List[ScoutNotice] = []
87
+
88
+        env_result = os.environ.get("AMBASSADOR_SCOUT_RESULT", None)
89
+        if env_result:
90
+            force_result = json.loads(env_result)
91
+
92
+        result: Optional[dict] = force_result
93
+        result_was_cached: bool = False
94
+
95
+        if not result:
96
+            if 'runtime' not in kwargs:
97
+                kwargs['runtime'] = self.runtime
98
+
99
+            if 'namespace' not in kwargs:
100
+                kwargs['namespace'] = self.namespace
101
+
102
+            # How long since the last Scout update? If it's been more than an hour,
103
+            # check Scout again.
104
+
105
+            now = datetime.datetime.now()
106
+
107
+            if (now - self._last_update) > self._update_frequency:
108
+                if self.scout:
109
+                    result = self.scout.report(**kwargs)
110
+
111
+                    self._last_update = now
112
+                    self._last_result = dict(**result)
113
+                else:
114
+                    result = { "scout": "unavailable: %s" % self._scout_error }
115
+                    _notices.append({ "level": "debug",
116
+                                      "message": "scout temporarily unavailable: %s" % self._scout_error })
117
+
118
+                # Whether we could talk to Scout or not, update the timestamp so we don't
119
+                # try again too soon.
120
+                result_timestamp = datetime.datetime.now()
121
+            else:
122
+                _notices.append({ "level": "debug", "message": "Returning cached result" })
123
+                result = dict(**self._last_result)
124
+                result_was_cached = True
125
+
126
+                result_timestamp = self._last_update
127
+        else:
128
+            _notices.append({ "level": "debug", "message": "Returning forced result" })
129
+            result_timestamp = datetime.datetime.now()
130
+
131
+        if not self.semver:
132
+            _notices.append({
133
+                "level": "warning",
134
+                "message": "Ambassador has invalid version '%s'??!" % self.version
135
+            })
136
+
137
+        result['cached'] = result_was_cached
138
+        result['timestamp'] = result_timestamp.timestamp()
139
+
140
+        # Do version & notices stuff.
141
+        if 'latest_version' in result:
142
+            latest_version = result['latest_version']
143
+            latest_semver = self.get_semver(latest_version)
144
+
145
+            if latest_semver:
146
+                self._latest_version = latest_version
147
+                self._latest_semver = latest_semver
148
+            else:
149
+                _notices.append({
150
+                    "level": "warning",
151
+                    "message": "Scout returned invalid version '%s'??!" % latest_version
152
+                })
153
+
154
+        if (self._latest_semver and ((not self.semver) or
155
+                                     (self._latest_semver > self.semver))):
156
+            _notices.append({
157
+                "level": "info",
158
+                "message": "Upgrade available! to Ambassador version %s" % self._latest_semver
159
+            })
160
+
161
+        if 'notices' in result:
162
+            _notices.extend(result['notices'])
163
+
164
+        self._notices = _notices
165
+
166
+        return result, self._notices
167
+
168
+    @staticmethod
169
+    def get_semver(version_string: str) -> Optional[semantic_version.Version]:
170
+        semver = None
171
+
172
+        try:
173
+            semver = semantic_version.Version(version_string)
174
+        except ValueError:
175
+            pass
176
+
177
+        return semver
178
+
179
+    @staticmethod
180
+    def parse_git_description(version: str, build: BuildInfo) -> str:
181
+        # Here's what we get for various kinds of builds:
182
+        #
183
+        # Random (clean):
184
+        # Version:               shared-dev-tgr606-f60229d
185
+        # build.git.branch:      shared/dev/tgr606
186
+        # build.git.commit:      f60229d
187
+        # build.git.dirty:       False
188
+        # build.git.description: 0.50.0-tt2-1-gf60229d
189
+        # --> 0.50.0-local+gf60229d
190
+        #
191
+        # Random (dirty):
192
+        # Version:               shared-dev-tgr606-f60229d-dirty
193
+        # build.git.branch:      shared/dev/tgr606
194
+        # build.git.commit:      f60229d
195
+        # build.git.dirty:       True
196
+        # build.git.description: 0.50.0-tt2-1-gf60229d
197
+        # --> 0.50.0-local+gf60229d.dirty
198
+        #
199
+        # EA:
200
+        # Version:               0.50.0
201
+        # build.git.branch:      0.50.0-ea2
202
+        # build.git.commit:      05aefd5
203
+        # build.git.dirty:       False
204
+        # build.git.description: 0.50.0-ea2
205
+        # --> 0.50.0-ea2
206
+        #
207
+        # RC
208
+        # Version:               0.40.0
209
+        # build.git.branch:      0.40.0-rc1
210
+        # build.git.commit:      d450dca
211
+        # build.git.dirty:       False
212
+        # build.git.description: 0.40.0-rc1
213
+        # --> 0.40.0-rc1
214
+        #
215
+        # GA
216
+        # Version:               0.40.0
217
+        # build.git.branch:      0.40.0
218
+        # build.git.commit:      e301a90
219
+        # build.git.dirty:       False
220
+        # build.git.description: 0.40.0
221
+        # --> 0.40.0
222
+
223
+        # Start by assuming that the version is sane and we needn't
224
+        # tack any build metadata onto it.
225
+
226
+        build_elements = []
227
+
228
+        if not AmbScout.reTaggedBranch.search(version):
229
+            # This isn't a proper sane version. It must be a local build. Per
230
+            # Scout's rules, anything with semver build metadata is treated as a
231
+            # dev version, so we need to make sure our returned version has some.
232
+            #
233
+            # Start by assuming that we won't find a useable version in the
234
+            # description, and must fall back to 0.0.0.
235
+            build_version = "0.0.0"
236
+            desc_delta = None
237
+
238
+            # OK. Can we find a version from what the git description starts
239
+            # with? If so, the upgrade logic in the diagnostics will work more
240
+            # sanely.
241
+
242
+            m = AmbScout.reGitDescription.search(build.git.description)
243
+
244
+            if m:
245
+                # OK, the description ends with -$delta-g$commit at least, so
246
+                # it may start with a version. Strip off the matching text and
247
+                # remember the delta and commit.
248
+
249
+                desc_delta = m.group(1)
250
+                desc = build.git.description[0:m.start()]
251
+
252
+                # Does the remaining description match a sane version?
253
+                m = AmbScout.reTaggedBranch.search(desc)
254
+
255
+                if m:
256
+                    # Yes. Use it as the base version.
257
+                    build_version = m.group(1)
258
+
259
+            # We'll use prerelease "local", and include the branch and such
260
+            # in the build metadata.
261
+            version = '%s-local' % build_version
262
+
263
+            # Does the commit not appear in a build element?
264
+            build_elements = []
265
+
266
+            if desc_delta:
267
+                build_elements.append(desc_delta)
268
+
269
+            build_elements.append("g%s" % build.git.commit)
270
+
271
+            # If this branch is dirty, append a build element of "dirty".
272
+            if build.git.dirty:
273
+                build_elements.append('dirty')
274
+
275
+        # Finally, put it all together.
276
+        if build_elements:
277
+            version += "+%s" % ('.'.join(build_elements))
278
+
279
+        return version

+ 70
- 58
ambassador/ambassador/cli.py View File

@@ -27,63 +27,62 @@ import yaml
27 27
 import clize
28 28
 from clize import Parameter
29 29
 
30
-from .config import Config, fetch_resources
31
-from .ir import IR
32
-from .diagnostics import Diagnostics
30
+from . import Scout, ScoutNotice, Config, IR, Diagnostics, Version
31
+from .config import fetch_resources
33 32
 from .envoy import V1Config
34 33
 from .envoy import V2Config
35 34
 
36 35
 from .utils import RichStatus
37 36
 
38
-from .VERSION import Version
39
-
40 37
 __version__ = Version
41 38
 
42 39
 logging.basicConfig(
43
-    level=logging.DEBUG, # if appDebug else logging.INFO,
40
+    level=logging.DEBUG,  # if appDebug else logging.INFO,
44 41
     format="%%(asctime)s ambassador %s %%(levelname)s: %%(message)s" % __version__,
45 42
     datefmt="%Y-%m-%d %H:%M:%S"
46 43
 )
47 44
 
48
-# logging.getLogger("datawire.scout").setLevel(logging.DEBUG)
45
+logging.getLogger("datawire.scout").setLevel(logging.DEBUG)
49 46
 logger = logging.getLogger("ambassador")
50 47
 logger.setLevel(logging.DEBUG)
51 48
 
49
+
52 50
 def handle_exception(what, e, **kwargs):
53 51
     tb = "\n".join(traceback.format_exception(*sys.exc_info()))
54 52
 
55
-    # if Config.scout:
56
-    #     result = Config.scout_report(action=what, mode="cli", exception=str(e), traceback=tb,
57
-    #                                  runtime=Config.runtime, **kwargs)
58
-    #
59
-    #     logger.debug("Scout %s, result: %s" %
60
-    #                  ("disabled" if Config.scout.disabled else "enabled", result))
53
+    scout = Scout()
54
+    result, notices = scout.report(action=what, mode="cli", exception=str(e), traceback=tb, **kwargs)
55
+
56
+    logger.debug("Scout %s, result: %s" %
57
+                 ("enabled" if scout._scout else "disabled", result))
61 58
 
62 59
     logger.error("%s: %s\n%s" % (what, e, tb))
63 60
 
64
-    show_notices()
65
-
66
-def show_notices(printer=logger.log):
67
-    # if Config.scout_notices:
68
-    #     for notice in Config.scout_notices:
69
-    #         try:
70
-    #             if isinstance(notice, str):
71
-    #                 printer(logging.WARNING, notice)
72
-    #             else:
73
-    #                 lvl = notice['level'].upper()
74
-    #                 msg = notice['message']
75
-    #
76
-    #                 if isinstance(lvl, str):
77
-    #                     lvl = getattr(logging, lvl, logging.INFO)
78
-    #
79
-    #                 printer(lvl, msg)
80
-    #         except KeyError:
81
-    #             printer(logging.WARNING, json.dumps(notice))
82
-    print("CANNOT SHOW NOTICES RIGHT NOW")
61
+    show_notices(notices)
62
+
63
+
64
+def show_notices(notices: Optional[List[ScoutNotice]], printer=logger.log):
65
+    if notices:
66
+        for notice in notices:
67
+            try:
68
+                if isinstance(notice, str):
69
+                    printer(logging.WARNING, notice)
70
+                else:
71
+                    lvl = notice['level'].upper()
72
+                    msg = notice['message']
73
+
74
+                    if isinstance(lvl, str):
75
+                        lvl = getattr(logging, lvl, logging.INFO)
76
+
77
+                    printer(lvl, msg)
78
+            except KeyError:
79
+                printer(logging.WARNING, json.dumps(notice))
80
+
83 81
 
84 82
 def stdout_printer(lvl, msg):
85 83
     print("%s: %s" % (logging.getLevelName(lvl), msg))
86 84
 
85
+
87 86
 def version():
88 87
     """
89 88
     Show Ambassador's version
@@ -91,26 +90,29 @@ def version():
91 90
 
92 91
     print("Ambassador %s" % __version__)
93 92
 
94
-    # if Config.scout:
95
-    #     Config.scout_report(action="version", mode="cli")
96
-    #     show_notices(printer=stdout_printer)
93
+    scout = Scout()
94
+
95
+    print("Ambassador Scout version %s" % scout.version)
96
+    print("Ambassador Scout semver  %s" % scout.get_semver(scout.version))
97
+
98
+    result, notices = scout.report(action="version", mode="cli")
99
+    show_notices(notices, printer=stdout_printer)
100
+
97 101
 
98 102
 def showid():
99 103
     """
100 104
     Show Ambassador's installation ID
101 105
     """
102 106
 
103
-    # if Config.scout:
104
-    #     print("%s" % Config.scout.install_id)
105
-    #
106
-    #     Config.scout_report(action="showid", mode="cli")
107
-    #
108
-    #     show_notices(printer=stdout_printer)
109
-    # else:
110
-    #     print("unknown")
111
-    print("CANNOT SHOW ID RIGHT NOW")
112
-
113
-def dump(config_dir_path:Parameter.REQUIRED, *,
107
+    scout = Scout()
108
+
109
+    print("Ambassador Scout installation ID %s" % scout.install_id)
110
+
111
+    result, notices = scout.report(action="showid", mode="cli")
112
+    show_notices(notices, printer=stdout_printer)
113
+
114
+
115
+def dump(config_dir_path: Parameter.REQUIRED, *,
114 116
          k8s=False, aconf=False, ir=False, v1=False, v2=False, diag=False):
115 117
     """
116 118
     Dump various forms of an Ambassador configuration for debugging
@@ -130,7 +132,7 @@ def dump(config_dir_path:Parameter.REQUIRED, *,
130 132
     if not (aconf or ir or v1 or v2 or diag):
131 133
         aconf = True
132 134
         ir = True
133
-        v1 = True
135
+        v1 = False  # Default to NOT dumping V1 any more.
134 136
         v2 = True
135 137
         diag = False
136 138
 
@@ -141,6 +143,7 @@ def dump(config_dir_path:Parameter.REQUIRED, *,
141 143
     dump_diag = diag
142 144
 
143 145
     od = {}
146
+    diagconfig = None
144 147
 
145 148
     try:
146 149
         resources = fetch_resources(config_dir_path, logger, k8s=k8s)
@@ -151,28 +154,31 @@ def dump(config_dir_path:Parameter.REQUIRED, *,
151 154
             od['aconf'] = aconf.as_dict()
152 155
 
153 156
         ir = IR(aconf)
154
-        v1config = V1Config(ir)
155
-        elements = v1config.elements
156
-
157
-        v2config = V2Config(ir)
158 157
 
159 158
         if dump_ir:
160 159
             od['ir'] = ir.as_dict()
161 160
 
162 161
         if dump_v1:
162
+            v1config = V1Config(ir)
163
+            diagconfig = v1config
163 164
             od['v1'] = v1config.as_dict()
164 165
 
165 166
         if dump_v2:
167
+            v2config = V2Config(ir)
168
+            diagconfig = v2config
166 169
             od['v2'] = v2config.as_dict()
167
-            elements = v2config.elements
168 170
 
169 171
         if dump_diag:
170
-            diag = Diagnostics(ir, v1config)
172
+            diag = Diagnostics(ir, diagconfig)
171 173
             od['diag'] = diag.as_dict()
172
-            od['elements'] = elements
174
+            od['elements'] = diagconfig.elements
173 175
 
174 176
         json.dump(od, sys.stdout, sort_keys=True, indent=4)
175 177
         sys.stdout.write("\n")
178
+
179
+        scout = Scout()
180
+        result, notices = scout.report(action="dump", mode="cli")
181
+        show_notices(notices)
176 182
     except Exception as e:
177 183
         handle_exception("EXCEPTION from dump", e,
178 184
                          config_dir_path=config_dir_path)
@@ -180,7 +186,8 @@ def dump(config_dir_path:Parameter.REQUIRED, *,
180 186
         # This is fatal.
181 187
         sys.exit(1)
182 188
 
183
-def validate(config_dir_path:Parameter.REQUIRED, *, k8s=False):
189
+
190
+def validate(config_dir_path: Parameter.REQUIRED, *, k8s=False):
184 191
     """
185 192
     Validate an Ambassador configuration
186 193
 
@@ -189,7 +196,8 @@ def validate(config_dir_path:Parameter.REQUIRED, *, k8s=False):
189 196
     """
190 197
     config(config_dir_path, os.devnull, k8s=k8s, exit_on_error=True)
191 198
 
192
-def config(config_dir_path:Parameter.REQUIRED, output_json_path:Parameter.REQUIRED, *,
199
+
200
+def config(config_dir_path: Parameter.REQUIRED, output_json_path: Parameter.REQUIRED, *,
193 201
            check=False, k8s=False, ir=None, aconf=None, exit_on_error=False):
194 202
     """
195 203
     Generate an Envoy configuration
@@ -221,7 +229,7 @@ def config(config_dir_path:Parameter.REQUIRED, output_json_path:Parameter.REQUIR
221 229
             output_exists = True
222 230
 
223 231
             try:
224
-                x = json.loads(open(output_json_path, "r").read())
232
+                json.loads(open(output_json_path, "r").read())
225 233
             except FileNotFoundError:
226 234
                 logger.debug("output file does not exist")
227 235
                 output_exists = False
@@ -281,7 +289,9 @@ def config(config_dir_path:Parameter.REQUIRED, output_json_path:Parameter.REQUIR
281 289
             else:
282 290
                 logger.error("Could not generate new Envoy configuration: %s" % rc.error)
283 291
 
284
-        show_notices()
292
+        scout = Scout()
293
+        result, notices = scout.report(action="config", mode="cli")
294
+        show_notices(notices)
285 295
     except Exception as e:
286 296
         handle_exception("EXCEPTION from config", e,
287 297
                          config_dir_path=config_dir_path, output_json_path=output_json_path)
@@ -289,6 +299,7 @@ def config(config_dir_path:Parameter.REQUIRED, output_json_path:Parameter.REQUIR
289 299
         # This is fatal.
290 300
         sys.exit(1)
291 301
 
302
+
292 303
 def main():
293 304
     clize.run([config, dump, validate], alt=[version, showid],
294 305
               description="""
@@ -303,5 +314,6 @@ def main():
303 314
               to see Ambassador's version.
304 315
               """)
305 316
 
317
+
306 318
 if __name__ == "__main__":
307 319
     main()

+ 0
- 5
ambassador/ambassador/config/config.py View File

@@ -47,8 +47,6 @@ class Config:
47 47
     # CLASS VARIABLES
48 48
     # When using multiple Ambassadors in one cluster, use AMBASSADOR_ID to distinguish them.
49 49
     ambassador_id: ClassVar[str] = os.environ.get('AMBASSADOR_ID', 'default')
50
-    runtime: ClassVar[str] = "kubernetes" if os.environ.get('KUBERNETES_SERVICE_HOST', None) else "docker"
51
-    namespace: ClassVar[str] = os.environ.get('AMBASSADOR_NAMESPACE', 'default')
52 50
 
53 51
     # INSTANCE VARIABLES
54 52
     current_resource: Optional[ACResource] = None
@@ -76,9 +74,6 @@ class Config:
76 74
         self.schema_dir_path = schema_dir_path
77 75
 
78 76
         self.logger = logging.getLogger("ambassador.config")
79
-
80
-        # self.logger.debug("Scout version %s" % Config.scout_version)
81
-        self.logger.debug("Runtime       %s" % Config.runtime)
82 77
         self.logger.debug("SCHEMA DIR    %s" % os.path.abspath(self.schema_dir_path))
83 78
 
84 79
         self._reset()

Loading…
Cancel
Save