~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: Thomi Richards
  • Date: 2014-06-27 20:02:44 UTC
  • mto: (629.2.9 nfss)
  • mto: This revision was merged to the branch mainline in revision 636.
  • Revision ID: thomi.richards@canonical.com-20140627200244-zi7dwxnyw38ypr2f
Initial version.

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
    database_connection = nfss.database.get_connection_for_request()
 
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
    database_connection.close()
 
112
 
 
113
    valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
 
114
    filename = ''.join(c for c in name if c in valid_chars)
 
115
    filename = filename.replace(' ', '_') + '_insert.py'
 
116
    while True:
 
117
        try:
 
118
            with open(filename, 'w') as f:
 
119
                f.write(
 
120
                    INSERT_SCRIPT_TEMPLATE.format(
 
121
                        client_access_key=access_key,
 
122
                        resource_owner_key=owner_key,
 
123
                        resource_owner_secret=owner_secret,
 
124
                    )
 
125
                )
 
126
        except IOError:
 
127
            print("Cannot write to the default location (%s)" % filename)
 
128
            filename = input("Where should the new script be written to? ")
 
129
        else:
 
130
            print(
 
131
                "%r has been written. Use this to insert data into the data store." %
 
132
                filename
 
133
            )
 
134
            break
 
135
 
 
136
 
 
137
def keys_del(client_key):
 
138
    with nfss.database.get_scoped_connection() as db_connection:
 
139
        if not nfss.database.get_auth_client_key_exists(
 
140
            db_connection,
 
141
            client_key
 
142
        ):
 
143
            print("Error: the client key '%s' does not exist. Use 'keys-list'")
 
144
            print(" to get a list of all the client access keys.")
 
145
            sys.exit(1)
 
146
        nfss.database.invalidate_client_key(db_connection, client_key)
 
147
        if not nfss.database.get_auth_client_key_exists(
 
148
            db_connection,
 
149
            client_key
 
150
        ):
 
151
            print("Client key has been successfully invalidated.")
 
152
        else:
 
153
            print("Client key has NOT been invalidated.")
 
154
 
 
155
 
 
156
def keys_list():
 
157
    with nfss.database.get_scoped_connection() as db_connection:
 
158
        for key in nfss.database.get_auth_client_key_list(db_connection):
 
159
            print(key)
 
160
 
 
161
 
 
162
def database_clean():
 
163
    with nfss.database.get_scoped_connection() as db_connection:
 
164
        nfss.database.clean_old_nonces(db_connection)
 
165
 
 
166
 
 
167
INSERT_SCRIPT_TEMPLATE = r'''#!/usr/bin/env python3
 
168
 
 
169
import json
 
170
import sys
 
171
from requests_oauthlib import OAuth1Session
 
172
 
 
173
# Note: The resource_owner_secret is *secret*, and must be kept secret. If
 
174
# you think it's been compromised, contact IS with your client access key
 
175
# and they can invalidate the old key and assign a new one.
 
176
client_access_key = {client_access_key!r}
 
177
resource_owner_key = {resource_owner_key!r}
 
178
resource_owner_secret = {resource_owner_secret!r}
 
179
backend = 'http://nfss.ubuntu.com/api/v1'
 
180
 
 
181
if len(sys.argv) != 3:
 
182
    print("Usage: %s <projectname> <testname>\n" % sys.argv[0])
 
183
    print("Pipe json test data to this script to insert it into the database.")
 
184
    sys.exit(1)
 
185
 
 
186
project = sys.argv[1]
 
187
test = sys.argv[2]
 
188
 
 
189
if sys.stdin.isatty():
 
190
    print("Error: Pipe json test data through this script, like so:")
 
191
    print("$ cat test_data | %s %s %s" % (sys.argv[0], project, test))
 
192
    sys.exit(2)
 
193
 
 
194
data = sys.stdin.read()
 
195
try:
 
196
    json.loads(data)
 
197
except ValueError as e:
 
198
    print("Error: Data does not appear to be valid json: %s" % e)
 
199
    sys.exit(3)
 
200
 
 
201
test_session = OAuth1Session(
 
202
    client_access_key,
 
203
    resource_owner_key=resource_owner_key,
 
204
    resource_owner_secret=resource_owner_secret
 
205
)
 
206
url = '/'.join((backend, project, test))
 
207
r = test_session.post(url, dict(data=data.encode()))
 
208
print(r.text)
 
209
'''
 
210
 
 
211
 
 
212
if __name__ == '__main__':
 
213
    main()