~larry-e-works/uci-engine/write-exitcode-to-file

« back to all changes in this revision

Viewing changes to nf-stats-service/nfss/__main__.py

  • Committer: Ubuntu CI Bot
  • Author(s): Thomi Richards, Robert Bruce Park
  • Date: 2014-07-01 23:04:05 UTC
  • mfrom: (629.2.18 nfss)
  • Revision ID: ubuntu_ci_bot-20140701230405-bwij2o5lga3iwyal
[r=Francis Ginther, PS Jenkins bot, Andy Doan] Initial import of non functional stats service app.  from Canonical CI Engineering

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python3
 
2
# Ubuntu CI Engine
 
3
# Copyright 2014 Canonical Ltd.
 
4
#
 
5
# This program is free software: you can redistribute it and/or modify it
 
6
# under the terms of the GNU Affero General Public License version 3, as
 
7
# published by the Free Software Foundation.
 
8
#
 
9
# This program is distributed in the hope that it will be useful, but
 
10
# WITHOUT ANY WARRANTY; without even the implied warranties of
 
11
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 
12
# PURPOSE.  See the GNU Affero General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU Affero General Public License
 
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
16
 
 
17
from oauthlib.common import (
 
18
    generate_client_id,
 
19
    generate_token,
 
20
)
 
21
from argparse import ArgumentParser
 
22
import string
 
23
from textwrap import dedent
 
24
import sys
 
25
 
 
26
import nfss
 
27
 
 
28
 
 
29
def main():
 
30
    parser = ArgumentParser('nfss')
 
31
    subparsers = parser.add_subparsers(help='Commands', dest="command")
 
32
 
 
33
    subparsers.add_parser(
 
34
        'keys-add',
 
35
        help="Generate a new set of access keys.",
 
36
    )
 
37
    parser_keys_del = subparsers.add_parser(
 
38
        'keys-del',
 
39
        help="Remove an existing set of access keys.",
 
40
    )
 
41
    parser_keys_del.add_argument(
 
42
        'client_key',
 
43
        help="The client access key you want to invalidate."
 
44
    )
 
45
    subparsers.add_parser(
 
46
        'keys-list',
 
47
        help="List current client access keys."
 
48
    )
 
49
    subparsers.add_parser(
 
50
        'database-migrate',
 
51
        help="Migrate the database.",
 
52
    )
 
53
    subparsers.add_parser(
 
54
        'database-clean',
 
55
        help="Run database maintenance tasks."
 
56
    )
 
57
    arguments = parser.parse_args()
 
58
    if arguments.command is None:
 
59
        parser.error("Missing command string.")
 
60
        return
 
61
 
 
62
    if arguments.command == 'keys-add':
 
63
        keys_add()
 
64
    elif arguments.command == 'keys-del':
 
65
        keys_del(arguments.client_key)
 
66
    elif arguments.command == 'keys-list':
 
67
        keys_list()
 
68
    elif arguments.command == 'database-migrate':
 
69
        nfss.db_migrate.main()
 
70
    elif arguments.command == 'database-clean':
 
71
        database_clean()
 
72
 
 
73
 
 
74
def keys_add():
 
75
    global INSERT_SCRIPT_TEMPLATE
 
76
    repeat = True
 
77
    name = description = poc = ""
 
78
    while repeat:
 
79
        name = input("Client name: ")
 
80
        poc = input("Point of contact (name & email address): ")
 
81
        description = input("Description of client: ")
 
82
        print(
 
83
            dedent(
 
84
                """
 
85
                Client Summary:
 
86
 
 
87
                Client Name: {}
 
88
                Point of Contact: {}
 
89
                Description: {}
 
90
 
 
91
                """.format(name, poc, description)
 
92
            )
 
93
        )
 
94
        correct = input("Is this information correct (y/n)? ")
 
95
        repeat = correct.lower().strip() == "n"
 
96
 
 
97
    access_key = generate_token()
 
98
    owner_key = generate_token()
 
99
    owner_secret = generate_client_id()
 
100
 
 
101
    with nfss.database.get_scoped_connection() as database_connection:
 
102
        nfss.database.auth_add_client_details(
 
103
            database_connection,
 
104
            name,
 
105
            description,
 
106
            poc,
 
107
            access_key,
 
108
            owner_key,
 
109
            owner_secret
 
110
        )
 
111
 
 
112
    valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
 
113
    filename = ''.join(c for c in name if c in valid_chars)
 
114
    filename = filename.replace(' ', '_') + '_insert.py'
 
115
    while True:
 
116
        try:
 
117
            with open(filename, 'w') as f:
 
118
                f.write(
 
119
                    INSERT_SCRIPT_TEMPLATE.format(
 
120
                        client_access_key=access_key,
 
121
                        resource_owner_key=owner_key,
 
122
                        resource_owner_secret=owner_secret,
 
123
                    )
 
124
                )
 
125
        except IOError:
 
126
            print("Cannot write to the default location (%s)" % filename)
 
127
            filename = input("Where should the new script be written to? ")
 
128
        else:
 
129
            print(
 
130
                "%r has been written. Use this to insert data into the data store." %
 
131
                filename
 
132
            )
 
133
            break
 
134
 
 
135
 
 
136
def keys_del(client_key):
 
137
    with nfss.database.get_scoped_connection() as db_connection:
 
138
        if not nfss.database.get_auth_client_key_exists(
 
139
            db_connection,
 
140
            client_key
 
141
        ):
 
142
            print("Error: the client key '%s' does not exist. Use 'keys-list'")
 
143
            print(" to get a list of all the client access keys.")
 
144
            sys.exit(1)
 
145
        nfss.database.invalidate_client_key(db_connection, client_key)
 
146
        if not nfss.database.get_auth_client_key_exists(
 
147
            db_connection,
 
148
            client_key
 
149
        ):
 
150
            print("Client key has been successfully invalidated.")
 
151
        else:
 
152
            print("Client key has NOT been invalidated.")
 
153
 
 
154
 
 
155
def keys_list():
 
156
    with nfss.database.get_scoped_connection() as db_connection:
 
157
        data = nfss.database.get_auth_client_key_list(db_connection)
 
158
        if data:
 
159
            keylen = max([len(r[0]) for r in data]) + 2
 
160
            namelen = max([len(r[1]) for r in data]) + 2
 
161
            desclen = max([len(r[2]) for r in data]) + 2
 
162
            format_str = "%%%ds %%%ds %%%ds %%s" % (keylen, namelen, desclen)
 
163
            print(format_str % ("Key:", "Name:", "Description:", "Contact:"))
 
164
            for key, name, desc, poc in data:
 
165
                print(format_str % (key, name, desc, poc))
 
166
        print("Total: %d keys" % len(data))
 
167
 
 
168
 
 
169
def database_clean():
 
170
    with nfss.database.get_scoped_connection() as db_connection:
 
171
        nfss.database.clean_old_nonces(db_connection)
 
172
 
 
173
 
 
174
INSERT_SCRIPT_TEMPLATE = r'''#!/usr/bin/env python3
 
175
 
 
176
import json
 
177
import sys
 
178
from requests_oauthlib import OAuth1Session
 
179
 
 
180
# Note: The resource_owner_secret is *secret*, and must be kept secret. If
 
181
# you think it's been compromised, contact IS with your client access key
 
182
# and they can invalidate the old key and assign a new one.
 
183
client_access_key = {client_access_key!r}
 
184
resource_owner_key = {resource_owner_key!r}
 
185
resource_owner_secret = {resource_owner_secret!r}
 
186
backend = 'http://nfss.ubuntu.com/api/v1'
 
187
 
 
188
if len(sys.argv) != 3:
 
189
    print("Usage: %s <projectname> <testname>\n" % sys.argv[0])
 
190
    print("Pipe json test data to this script to insert it into the database.")
 
191
    sys.exit(1)
 
192
 
 
193
project = sys.argv[1]
 
194
test = sys.argv[2]
 
195
 
 
196
if sys.stdin.isatty():
 
197
    print("Error: Pipe json test data through this script, like so:")
 
198
    print("$ cat test_data | %s %s %s" % (sys.argv[0], project, test))
 
199
    sys.exit(2)
 
200
 
 
201
data = sys.stdin.read()
 
202
try:
 
203
    json.loads(data)
 
204
except ValueError as e:
 
205
    print("Error: Data does not appear to be valid json: %s" % e)
 
206
    sys.exit(3)
 
207
 
 
208
test_session = OAuth1Session(
 
209
    client_access_key,
 
210
    resource_owner_key=resource_owner_key,
 
211
    resource_owner_secret=resource_owner_secret
 
212
)
 
213
url = '/'.join((backend, project, test))
 
214
r = test_session.post(url, dict(data=data.encode()))
 
215
print(r.text)
 
216
'''
 
217
 
 
218
 
 
219
if __name__ == '__main__':
 
220
    main()