987ebe16a5489c45f0b569b2ed449acc7a14e16d
[integration/packaging.git] / packages / vars.py
1 #!/usr/bin/env python
2
3 ##############################################################################
4 # Copyright (c) 2016 Daniel Farrell and Others.  All rights reserved.
5 #
6 # This program and the accompanying materials are made available under the
7 # terms of the Eclipse Public License v1.0 which accompanies this distribution,
8 # and is available at http://www.eclipse.org/legal/epl-v10.html
9 ##############################################################################
10
11 import datetime
12 import re
13 import subprocess
14 import sys
15 from urllib2 import urlopen
16
17 try:
18     from bs4 import BeautifulSoup
19     import requests
20     from requests.exceptions import HTTPError
21     import tzlocal
22 except ImportError:
23     sys.stderr.write("We recommend using our included Vagrant env.\n")
24     sys.stderr.write("Else, do `pip install -r requirements.txt` in a venv.\n")
25     raise
26
27
28 def extract_version(url):
29     """Determine ODL version information from the ODL tarball build URL
30
31     :arg str url: URL of the ODL tarball build for building RPMs
32
33     """
34     if "autorelease" in url:
35         # Autorelease URL does not include a date and hence date extraction
36         # logic is needed for RPM versioning.
37         # Docs:
38         #   https://wiki.opendaylight.org/view/Integration/Packaging/Versioning
39         # Substitute the part of the build URL not required with empty string
40         date_url = re.sub('distribution-karaf-.*\.tar\.gz$', '', url)
41         # Set date_url as an environment variable for it to be used in
42         # a subprocess
43         os.environ["date_url"] = date_url
44         # Extract ODL artifact's date by scraping data from the build URL
45         odl_date = subprocess.Popen(
46             "curl -s $date_url | grep tar.gz -A1 | tail -n1 |"
47             "sed \"s/<td>//g\" | sed \"s/\\n//g\" | awk '{print $3,$2,$6}' ",
48             shell=True, stdout=subprocess.PIPE,
49             stdin=subprocess.PIPE).stdout.read().rstrip().strip("</td>")
50         date = datetime.datetime.strptime(odl_date, "%d %b %Y").strftime(
51                                                                 '%Y%m%d')
52         # Search the ODL autorelease build URL to match the Build ID that
53         # follows "autorelease-". eg:
54         # https://nexus.opendaylight.org/content/repositories/autorelease-1533/
55         #  org/opendaylight/integration/distribution-karaf/0.4.4-Beryllium-SR4/
56         # build_id = 1533
57         build_id = re.search(r'\/(autorelease)-([0-9]+)\/', url).group(2)
58         pkg_version = "0.1." + date + "rel" + build_id
59     elif "snapshot" in url:
60         # Search the ODL snapshot build URL to match the date and the Build ID
61         # that are between "distribution-karaf" and ".tar.gz".
62         # eg: https://nexus.opendaylight.org/content/repositories/
63         #      opendaylight.snapshot/org/opendaylight/integration/
64         #      distribution-karaf/0.6.0-SNAPSHOT/
65         #      distribution-karaf-0.6.0-20161201.031047-2242.tar.gz
66         # build_id = 2242
67         # date = 20161201
68         odl_rpm = re.search(
69             r'\/(distribution-karaf)-'
70             r'([0-9]\.[0-9]\.[0-9])-([0-9]+)\.([0-9]+)-([0-9]+)\.(tar\.gz)',
71             url)
72         pkg_version = "0.1." + odl_rpm.group(3) + "snap" + odl_rpm.group(5)
73     elif "public" or "opendaylight.release" in url:
74         pkg_version = "1"
75     else:
76         raise ValueError("Unrecognized URL {}".format(url))
77
78     version = {}
79     # Search the ODL build URL to match 0.major.minor-codename-SR and extract
80     # version information. eg: release:
81     # https://nexus.opendaylight.org/content/repositories/public/org/
82     #  opendaylight/integration/distribution-karaf/0.3.3-Lithium-SR3/
83     #  distribution-karaf-0.3.3-Lithium-SR3.tar.gz
84     #     match: 0.3.3-Lithium-SR3
85     odl_version = re.search(r'\/(\d)\.(\d)\.(\d).(.*)\/', url)
86     version["version_major"] = odl_version.group(2)
87     version["version_minor"] = odl_version.group(3)
88     version["version_patch"] = "0"
89     version["pkg_version"] = pkg_version
90     version["codename"] = odl_version.group(4)
91     return version
92
93
94 def get_snap_url(version_major, version_minor):
95     """Fetches tarball url for snapshot releases using version information
96
97     :arg str version_major: Major version for snapshot build
98     :arg str version_minor: Minor version for snapshot build(optional)
99     :return arg snapshot_url: URL of the snapshot release
100     """
101     parent_dir = "https://nexus.opendaylight.org/content/repositories/" \
102                  "opendaylight.snapshot/org/opendaylight/integration/"\
103                  "distribution-karaf/"
104
105     # If the minor verison is given, get the sub-directory directly
106     # else, find the latest sub-directory
107     sub_dir = ''
108     snapshot_dir = ''
109     if version_minor:
110         sub_dir = '0.' + version_major + '.' + version_minor + '-SNAPSHOT/'
111         snapshot_dir = parent_dir + sub_dir
112     else:
113         subdir_url = urlopen(parent_dir)
114         content = subdir_url.read().decode('utf-8')
115         all_dirs = BeautifulSoup(content, 'html.parser')
116
117         # Loops through all the sub-directories present and stores the
118         # latest sub directory as sub-directories are already sorted
119         # in early to late order.
120         for tag in all_dirs.find_all('a', href=True):
121             # Checks if the sub-directory name is of the form
122             # '0.<major_version>.<minor_version>-SNAPSHOT'.
123             dir = re.search(r'\/(\d)\.(\d)\.(\d).(.*)\/', tag['href'])
124             # If the major version matches the argument provided
125             # store the minor version, else ignore.
126             if dir:
127                 if dir.group(2) == version_major:
128                     snapshot_dir = tag['href']
129                     version_minor = dir.group(3)
130
131     try:
132         req = requests.get(snapshot_dir)
133         req.raise_for_status()
134     except HTTPError:
135         print "Could not find the snapshot directory"
136     else:
137         urlpath = urlopen(snapshot_dir)
138         content = urlpath.read().decode('utf-8')
139         html_content = BeautifulSoup(content, 'html.parser')
140         # Loops through all the files present in `snapshot_dir`
141         # and stores the url of latest tarball because files are
142         # already sorted in early to late order.
143         for tag in html_content.find_all('a', href=True):
144             if tag['href'].endswith('tar.gz'):
145                 snapshot_url = tag['href']
146     return snapshot_url
147
148
149 def get_sysd_commit():
150     """Get latest Int/Pack repo commit hash"""
151
152     int_pack_repo = "https://github.com/opendaylight/integration-packaging.git"
153     # Get the commit hash at the tip of the master branch
154     args_git = ['git', 'ls-remote', int_pack_repo, "HEAD"]
155     args_awk = ['awk', '{print $1}']
156     references = subprocess.Popen(args_git, stdout=subprocess.PIPE,
157                                   shell=False)
158     sysd_commit = subprocess.check_output(args_awk, stdin=references.stdout,
159                                           shell=False).strip()
160
161     return sysd_commit
162
163
164 def get_java_version(version_major):
165     """Get the java_version dependency for ODL builds
166
167        :arg str version_major: OpenDaylight major version number
168        :return int java_version: Java version required by given ODL version
169     """
170     if version_major < 5:
171         java_version = 7
172     else:
173         java_version = 8
174     return java_version
175
176
177 def get_changelog_date(pkg_type):
178     """Get the changelog datetime formatted for the given package type
179
180     :arg str pkg_type: Type of datetime formatting (rpm, deb)
181     :return int changelog_date: Date or datetime formatted for given pkg_type
182     """
183     if pkg_type == "rpm":
184         # RPMs require a date of the format "Day Month Date Year". For example:
185         # Mon Jun 21 2017
186         return datetime.date.today().strftime("%a %b %d %Y")
187     elif pkg_type == "deb":
188         # Debs require both a date and time.
189         # Date must be of the format "Day, Date Month Year". For example:
190         # Mon, 21 Jun 2017
191         date = datetime.date.today().strftime("%a, %d %b %Y")
192         # Time must be of the format "HH:MM:SS +HHMM". For example:
193         # 15:01:16 +0530
194         time = datetime.datetime.now(tzlocal.get_localzone()).\
195             strftime("%H:%M:%S %z")
196         return "{} {}".format(date, time)
197     else:
198         raise ValueError("Unknown package type: {}".format(pkg_type))