Completed
Pull Request — master (#423)
by
unknown
02:03
created

GetScanExecutions()   C

Complexity

Conditions 8

Size

Total Lines 50

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 8
dl 0
loc 50
rs 5
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  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
import requests
17
import datetime
18
19
20
def GetScanExecutions(config, scan_id):
21
    """
22
    The template class for
23
24
    Returns: An blank Dict.
25
26
    Raises:
27
    ValueError: On lack of key in config.
28
    """
29
    results = {}
30
31
    url = "https://{}/api/scan/v1/scans/{}".format(config['api_host'], scan_id)
32
    headers = {"Accept": "application/json"}
33
34
    try:
35
        r = requests.get(url,
36
                         headers=headers,
37
                         auth=(config['api_key'], ''))
38
        r.raise_for_status()
39
    except:
40
        raise ValueError("HTTP error: %s on %s" % (r.status_code, r.url))
41
42
    try:
43
        data = r.json()
44
    except:
45
        raise ValueError("Invalid JSON")
46
    else:
47
        results = {'latest_complete': None, 'scans': []}
48
        for item in data:
49
            create_date = datetime.datetime.fromtimestamp(item['create_date'])
50
            finish_date = datetime.datetime.fromtimestamp(item['finish_date'])
51
            duration = finish_date - create_date
52
53
            results['scans'].append({"id": item['id'],
54
                                     "active": item['active'],
55
                                     "create_date": create_date.strftime('%Y-%m-%d %H:%M:%S'),
56
                                     "finish_date": finish_date.strftime('%Y-%m-%d %H:%M:%S'),
57
                                     "duration": str(duration)})
58
59
    # This list can be very large, limit to the last 10.
60
    results['scans'].sort(reverse=True)
61
    results['scans'] = results['scans'][0:10]
62
63
    # Find the latest ccmpleted scan..
64
    for item in results['scans']:
65
        if item['active'] is False:
66
            results['latest_complete'] = item['id']
67
            break
68
69
    return results
70