summaryrefslogtreecommitdiff
path: root/buildscripts/idl/check_versioned_api_commands_have_idl_definitions.py
blob: 0840dfadf8cd80a7128d70484a24e78a4839f9e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# Copyright (C) 2020-present MongoDB, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the Server Side Public License, version 1,
# as published by MongoDB, Inc.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# Server Side Public License for more details.
#
# You should have received a copy of the Server Side Public License
# along with this program. If not, see
# <http://www.mongodb.com/licensing/server-side-public-license>.
#
# As a special exception, the copyright holders give permission to link the
# code of portions of this program with the OpenSSL library under certain
# conditions as described in each individual source file and distribute
# linked combinations including the program with the OpenSSL library. You
# must comply with the Server Side Public License in all respects for
# all of the code used other than as permitted herein. If you modify file(s)
# with this exception, you may extend this exception to your version of the
# file(s), but you are not obligated to do so. If you do not wish to do so,
# delete this exception statement from your version. If you delete this
# exception statement from all source files in the program, then also delete
# it in the license file.
"""Check that mongod's and mongos's Versioned API commands are defined in IDL.

Call listCommands on mongod and mongos to assert they have the same set of commands in the given API
version, and assert all these commands are defined in IDL.
"""

import argparse
import logging
import os
import sys
from tempfile import TemporaryDirectory
from typing import Dict, List, Set

from pymongo import MongoClient

# Permit imports from "buildscripts".
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(__file__), '../../..')))

# pylint: disable=wrong-import-position
from buildscripts.resmokelib import configure_resmoke
from buildscripts.resmokelib.logging import loggers
from buildscripts.resmokelib.testing.fixtures import interface
from buildscripts.resmokelib.testing.fixtures.shardedcluster import ShardedClusterFixture
from buildscripts.resmokelib.testing.fixtures.standalone import MongoDFixture
from idl import parser, syntax
from idl.compiler import CompilerImportResolver

LOGGER_NAME = 'check-idl-definitions'
LOGGER = logging.getLogger(LOGGER_NAME)


def list_idls(directory: str) -> Set[str]:
    """Find all IDL files in the current directory."""
    return {
        os.path.join(dirpath, filename)
        for dirpath, dirnames, filenames in os.walk(directory) for filename in filenames
        if filename.endswith('.idl')
    }


def parse_idl(idl_path: str, import_directories: List[str]) -> syntax.IDLParsedSpec:
    """Parse an IDL file or throw an error."""
    parsed_doc = parser.parse(open(idl_path), idl_path, CompilerImportResolver(import_directories))

    if parsed_doc.errors:
        parsed_doc.errors.dump_errors()
        raise ValueError(f"Cannot parse {idl_path}")

    return parsed_doc


def get_command_definitions(api_version: str, directory: str,
                            import_directories: List[str]) -> Dict[str, syntax.Command]:
    """Get parsed IDL definitions of commands in a given API version."""

    LOGGER.info("Searching for command definitions in %s", directory)

    def gen():
        for idl_path in sorted(list_idls(directory)):
            for command in parse_idl(idl_path, import_directories).spec.symbols.commands:
                if command.api_version == api_version:
                    yield command.name, command

    idl_commands = dict(gen())
    LOGGER.debug("Found %s IDL commands in API Version %s", len(idl_commands), api_version)
    return idl_commands


def list_commands_for_api(api_version: str, mongod_or_mongos: str, install_dir: str) -> Set[str]:
    """Get a list of commands in a given API version by calling listCommands."""
    assert mongod_or_mongos in ("mongod", "mongos")
    logging.info("Calling listCommands on %s", mongod_or_mongos)
    dbpath = TemporaryDirectory()
    mongod_executable = os.path.join(install_dir, "mongod")
    mongos_executable = os.path.join(install_dir, "mongos")
    if mongod_or_mongos == "mongod":
        logger = loggers.new_fixture_logger("MongoDFixture", 0)
        logger.parent = LOGGER
        fixture: interface.Fixture = MongoDFixture(logger, 0, dbpath_prefix=dbpath.name,
                                                   mongod_executable=mongod_executable)
    else:
        logger = loggers.new_fixture_logger("ShardedClusterFixture", 0)
        logger.parent = LOGGER
        fixture = ShardedClusterFixture(logger, 0, dbpath_prefix=dbpath.name,
                                        mongos_executable=mongos_executable,
                                        mongod_executable=mongod_executable, mongod_options={})

    fixture.setup()
    fixture.await_ready()

    try:
        client = MongoClient(fixture.get_driver_connection_url())
        reply = client.admin.command('listCommands')
        commands = {
            name
            for name, info in reply['commands'].items() if api_version in info['apiVersions']
        }
        logging.info("Found %s commands in API Version %s on %s", len(commands), api_version,
                     mongod_or_mongos)
        return commands
    finally:
        fixture.teardown()


def assert_command_sets_equal(api_version: str, command_sets: Dict[str, Set[str]]):
    """Check that all sources have the same set of commands for a given API version."""
    LOGGER.info("Comparing %s command sets", len(command_sets))
    for name, commands in command_sets.items():
        LOGGER.info("--------- %s API Version %s commands --------------", name, api_version)
        for command in sorted(commands):
            LOGGER.info("%s", command)

    LOGGER.info("--------------------------------------------")
    it = iter(command_sets.items())
    name, commands = next(it)
    for other_name, other_commands in it:
        if commands != other_commands:
            if commands - other_commands:
                LOGGER.error("%s has commands not in %s: %s", name, other_name,
                             commands - other_commands)
            if other_commands - commands:
                LOGGER.error("%s has commands not in %s: %s", other_name, name,
                             other_commands - commands)
            # TODO(SERVER-51878): Enable this assertion.
            # raise AssertionError(
            #     f"{name} and {other_name} have different commands in API Version {api_version}")


def main():
    """Run the script."""
    arg_parser = argparse.ArgumentParser(description=__doc__)
    arg_parser.add_argument("--include", type=str, action="append",
                            help="Directory to search for IDL import files")
    arg_parser.add_argument("--installDir", dest="install_dir", metavar="INSTALL_DIR",
                            help="Directory to search for MongoDB binaries")
    arg_parser.add_argument("-v", "--verbose", action="count", help="Enable verbose logging")
    arg_parser.add_argument("api_version", metavar="API_VERSION", help="API Version to check")
    args = arg_parser.parse_args()

    # pylint: disable=protected-access
    configure_resmoke._update_config_vars(object)
    configure_resmoke._set_logging_config()

    # Configure Fixture logging.
    loggers.configure_loggers()
    loggers.new_job_logger(sys.argv[0], 0)
    logging.basicConfig(level=logging.WARNING)
    logging.getLogger(LOGGER_NAME).setLevel(logging.DEBUG if args.verbose else logging.INFO)

    command_sets = {}
    command_sets["mongod"] = list_commands_for_api(args.api_version, "mongod", args.install_dir)
    command_sets["mongos"] = list_commands_for_api(args.api_version, "mongos", args.install_dir)
    command_sets["idl"] = set(get_command_definitions(args.api_version, os.getcwd(), args.include))
    assert_command_sets_equal(args.api_version, command_sets)


if __name__ == "__main__":
    main()