Build deb's using common build.py
[integration/packaging.git] / 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 except ImportError:
22     sys.stderr.write("We recommend using our included Vagrant env.\n")
23     sys.stderr.write("Else, do `pip install -r requirements.txt` in a venv.\n")
24     raise
25
26
27 def extract_version(url):
28     """Determine ODL version information from the ODL tarball build URL
29
30     :arg str url: URL of the ODL tarball build for building RPMs
31
32     """
33     if "autorelease" in url:
34         # Autorelease URL does not include a date and hence date extraction
35         # logic is needed for RPM versioning.
36         # Docs:
37         #   https://wiki.opendaylight.org/view/Integration/Packaging/Versioning
38         # Substitute the part of the build URL not required with empty string
39         date_url = re.sub('distribution-karaf-.*\.tar\.gz$', '', url)
40         # Set date_url as an environment variable for it to be used in
41         # a subprocess
42         os.environ["date_url"] = date_url
43         # Extract ODL artifact's date by scraping data from the build URL
44         odl_date = subprocess.Popen(
45             "curl -s $date_url | grep tar.gz -A1 | tail -n1 |"
46             "sed \"s/<td>//g\" | sed \"s/\\n//g\" | awk '{print $3,$2,$6}' ",
47             shell=True, stdout=subprocess.PIPE,
48             stdin=subprocess.PIPE).stdout.read().rstrip().strip("</td>")
49         date = datetime.datetime.strptime(odl_date, "%d %b %Y").strftime(
50                                                                 '%Y%m%d')
51         # Search the ODL autorelease build URL to match the Build ID that
52         # follows "autorelease-". eg:
53         # https://nexus.opendaylight.org/content/repositories/autorelease-1533/
54         #  org/opendaylight/integration/distribution-karaf/0.4.4-Beryllium-SR4/
55         # build_id = 1533
56         build_id = re.search(r'\/(autorelease)-([0-9]+)\/', url).group(2)
57         pkg_version = "0.1." + date + "rel" + build_id
58     elif "snapshot" in url:
59         # Search the ODL snapshot build URL to match the date and the Build ID
60         # that are between "distribution-karaf" and ".tar.gz".
61         # eg: https://nexus.opendaylight.org/content/repositories/
62         #      opendaylight.snapshot/org/opendaylight/integration/
63         #      distribution-karaf/0.6.0-SNAPSHOT/
64         #      distribution-karaf-0.6.0-20161201.031047-2242.tar.gz
65         # build_id = 2242
66         # date = 20161201
67         odl_rpm = re.search(
68             r'\/(distribution-karaf)-'
69             r'([0-9]\.[0-9]\.[0-9])-([0-9]+)\.([0-9]+)-([0-9]+)\.(tar\.gz)',
70             url)
71         pkg_version = "0.1." + odl_rpm.group(3) + "snap" + odl_rpm.group(5)
72     elif "public" or "opendaylight.release" in url:
73         pkg_version = "1"
74     else:
75         raise ValueError("Unrecognized URL {}".format(url))
76
77     version = {}
78     # Search the ODL build URL to match 0.major.minor-codename-SR and extract
79     # version information. eg: release:
80     # https://nexus.opendaylight.org/content/repositories/public/org/
81     #  opendaylight/integration/distribution-karaf/0.3.3-Lithium-SR3/
82     #  distribution-karaf-0.3.3-Lithium-SR3.tar.gz
83     #     match: 0.3.3-Lithium-SR3
84     odl_version = re.search(r'\/(\d)\.(\d)\.(\d).(.*)\/', url)
85     version["version_major"] = odl_version.group(2)
86     version["version_minor"] = odl_version.group(3)
87     version["version_patch"] = "0"
88     version["pkg_version"] = pkg_version
89     version["codename"] = odl_version.group(4)
90     return version
91
92
93 def get_snap_url(version_major, version_minor):
94     """Fetches tarball url for snapshot releases using version information
95
96     :arg str version_major: Major version for snapshot build
97     :arg str version_minor: Minor version for snapshot build(optional)
98     :return arg snapshot_url: URL of the snapshot release
99     """
100     parent_dir = "https://nexus.opendaylight.org/content/repositories/" \
101                  "opendaylight.snapshot/org/opendaylight/integration/"\
102                  "distribution-karaf/"
103
104     # If the minor verison is given, get the sub-directory directly
105     # else, find the latest sub-directory
106     sub_dir = ''
107     snapshot_dir = ''
108     if version_minor:
109         sub_dir = '0.' + version_major + '.' + version_minor + '-SNAPSHOT/'
110         snapshot_dir = parent_dir + sub_dir
111     else:
112         subdir_url = urlopen(parent_dir)
113         content = subdir_url.read().decode('utf-8')
114         all_dirs = BeautifulSoup(content, 'html.parser')
115
116         # Loops through all the sub-directories present and stores the
117         # latest sub directory as sub-directories are already sorted
118         # in early to late order.
119         for tag in all_dirs.find_all('a', href=True):
120             # Checks if the sub-directory name is of the form
121             # '0.<major_version>.<minor_version>-SNAPSHOT'.
122             dir = re.search(r'\/(\d)\.(\d)\.(\d).(.*)\/', tag['href'])
123             # If the major version matches the argument provided
124             # store the minor version, else ignore.
125             if dir:
126                 if dir.group(2) == version_major:
127                     snapshot_dir = tag['href']
128                     version_minor = dir.group(3)
129
130     try:
131         req = requests.get(snapshot_dir)
132         req.raise_for_status()
133     except HTTPError:
134         print "Could not find the snapshot directory"
135     else:
136         urlpath = urlopen(snapshot_dir)
137         content = urlpath.read().decode('utf-8')
138         html_content = BeautifulSoup(content, 'html.parser')
139         # Loops through all the files present in `snapshot_dir`
140         # and stores the url of latest tarball because files are
141         # already sorted in early to late order.
142         for tag in html_content.find_all('a', href=True):
143             if tag['href'].endswith('tar.gz'):
144                 snapshot_url = tag['href']
145     return snapshot_url
146
147
148 def get_sysd_commit():
149     """Get latest Int/Pack repo commit hash"""
150
151     int_pack_repo = "https://github.com/opendaylight/integration-packaging.git"
152     # Get the commit hash at the tip of the master branch
153     args_git = ['git', 'ls-remote', int_pack_repo, "HEAD"]
154     args_awk = ['awk', '{print $1}']
155     references = subprocess.Popen(args_git, stdout=subprocess.PIPE,
156                                   shell=False)
157     sysd_commit = subprocess.check_output(args_awk, stdin=references.stdout,
158                                           shell=False).strip()
159
160     return sysd_commit
161
162
163 def get_java_version(version_major):
164     """Get the java_version dependency for ODL builds
165
166        :arg str version_major: OpenDaylight major version number
167        :return int java_version: Java version required by given ODL version
168     """
169     if version_major < 5:
170         java_version = 7
171     else:
172         java_version = 8
173     return java_version