opendaylight.service Restart=on-failure
[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 os
13 import re
14 import subprocess
15 import sys
16 from urllib2 import urlopen
17
18 try:
19     from bs4 import BeautifulSoup
20     import requests
21     from requests.exceptions import HTTPError
22     import tzlocal
23 except ImportError:
24     sys.stderr.write("We recommend using our included Vagrant env.\n")
25     sys.stderr.write("Else, do `pip install -r requirements.txt` in a venv.\n")
26     raise
27
28
29 def extract_version(url):
30     """Determine ODL version information from the ODL tarball build URL
31
32     :arg str url: URL of the ODL tarball build for building RPMs
33
34     """
35     if "autorelease" in url:
36         # Autorelease URL does not include a date and hence date extraction
37         # logic is needed for RPM versioning.
38         # Docs:
39         #   https://wiki.opendaylight.org/view/Integration/Packaging/Versioning
40         # Substitute the part of the build URL not required with empty string
41         date_url = re.sub('distribution-karaf-.*\.tar\.gz$', '', url)
42         # Set date_url as an environment variable for it to be used in
43         # a subprocess
44         os.environ["date_url"] = date_url
45         # Extract ODL artifact's date by scraping data from the build URL
46         odl_date = subprocess.Popen(
47             "curl -s $date_url | grep tar.gz -A1 | tail -n1 |"
48             "sed \"s/<td>//g\" | sed \"s/\\n//g\" | awk '{print $3,$2,$6}' ",
49             shell=True, stdout=subprocess.PIPE,
50             stdin=subprocess.PIPE).stdout.read().rstrip().strip("</td>")
51         date = datetime.datetime.strptime(odl_date, "%d %b %Y").strftime(
52                                                                 '%Y%m%d')
53         # Search the ODL autorelease build URL to match the Build ID that
54         # follows "autorelease-". eg:
55         # https://nexus.opendaylight.org/content/repositories/autorelease-1533/
56         #  org/opendaylight/integration/distribution-karaf/0.4.4-Beryllium-SR4/
57         # build_id = 1533
58         build_id = re.search(r'\/(autorelease)-([0-9]+)\/', url).group(2)
59         pkg_version = "0.1." + date + "rel" + build_id
60     elif "snapshot" in url:
61         # Search the ODL snapshot build URL to match the date and the Build ID
62         # that are between "distribution-karaf" and ".tar.gz".
63         # eg: https://nexus.opendaylight.org/content/repositories/
64         #      opendaylight.snapshot/org/opendaylight/integration/
65         #      distribution-karaf/0.6.0-SNAPSHOT/
66         #      distribution-karaf-0.6.0-20161201.031047-2242.tar.gz
67         # build_id = 2242
68         # date = 20161201
69         odl_rpm = re.search(
70             r'([0-9]\.[0-9]\.[0-9])-([0-9]+)\.([0-9]+)-([0-9]+)\.', url)
71         pkg_version = "0.1." + odl_rpm.group(2) + "snap" + odl_rpm.group(4)
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
174
175
176 def get_changelog_date(pkg_type):
177     """Get the changelog datetime formatted for the given package type
178
179     :arg str pkg_type: Type of datetime formatting (rpm, deb)
180     :return int changelog_date: Date or datetime formatted for given pkg_type
181     """
182     if pkg_type == "rpm":
183         # RPMs require a date of the format "Day Month Date Year". For example:
184         # Mon Jun 21 2017
185         return datetime.date.today().strftime("%a %b %d %Y")
186     elif pkg_type == "deb":
187         # Debs require both a date and time.
188         # Date must be of the format "Day, Date Month Year". For example:
189         # Mon, 21 Jun 2017
190         date = datetime.date.today().strftime("%a, %d %b %Y")
191         # Time must be of the format "HH:MM:SS +HHMM". For example:
192         # 15:01:16 +0530
193         time = datetime.datetime.now(tzlocal.get_localzone()).\
194             strftime("%H:%M:%S %z")
195         return "{} {}".format(date, time)
196     else:
197         raise ValueError("Unknown package type: {}".format(pkg_type))