Fixed issue with git fetch timeout or server down.
[apps/native/sample/sample-core-components.git] / tool / development / buildbot / nativesamples.py
1 # -*- coding: utf-8 -*-
2 import sys, os
3 import sqlite3
4 import ConfigParser
5 import subprocess
6 import re
7 import json
8 from pygerrit.ssh import GerritSSHClient
9 import smtplib
10 import base64
11 import traceback
12 import datetime
13 import tempfile
14 import xml.etree.ElementTree as ET
15
16 # Import the email modules we'll need
17 from email.mime.text import MIMEText
18 from email.mime.multipart import MIMEMultipart
19
20 reload(sys)
21 sys.setdefaultencoding('utf-8')
22
23 def numberOfProcesses(pgrepArg):
24         numberOfPollingProcesses = "0"
25         try:
26                 numberOfPollingProcesses = subprocess.check_output(["pgrep", "-c", "-f", pgrepArg])
27         except subprocess.CalledProcessError as err:
28                 numberOfPollingProcesses = err.output
29         return int(numberOfPollingProcesses)
30
31
32 class NativeSamplesConfig:
33         configFilePath = None
34         gerritServerName = None
35         gerritUser = None
36         gerritPort = None
37         gerritSshPrefixUrl = None
38         tizenSdkPath = None
39         sampleCoreComponentsPath = None
40         tizenBinary = None
41         tccBinary = None
42         checkpatchTizenBinary = None
43         convertToSampleProjectBinary = None
44         nativeSampleProjectList = None
45
46         emailNotificationsSmtpServerName = None
47         emailNotificationsSmtpPort = None
48         emailNotificationsSmtpUser = None
49         emailNotificationsSmtpB64EncodedPassword = None
50         emailNotificationsMailFrom = None
51         emailNotificationsMailTo = None
52         emailNotificationsMailCc = None
53         emailNotificationsMailBcc = None
54
55         def __init__(self, configFilePath = None):
56                 if configFilePath is not None:
57                         self.readConfigFile(configFilePath)
58         def readConfigFile(self, configFilePath):
59                 if os.path.exists(configFilePath):
60                         self.configFilePath = configFilePath
61                         config = ConfigParser.SafeConfigParser({'GerritServerName': None,
62                                                                                                         'GerritUser': None,
63                                                                                                         'GerritPort': None,
64                                                                                                         'TizenSdkPath': None,
65                                                                                                         'SampleCoreComponentsPath': None,
66                                                                                                         'SmtpServerName': None,
67                                                                                                         'SmtpPort': None,
68                                                                                                         'SmtpUser': None,
69                                                                                                         'SmtpB64EncodedPassword': None,
70                                                                                                         'MailFrom': None,
71                                                                                                         'MailTo': None,
72                                                                                                         'MailCc': None,
73                                                                                                         'MailBcc': None})
74                         config.read(configFilePath)
75                         self.gerritServerName =  config.get('Gerrit', 'GerritServerName')
76                         self.gerritUser = config.get('Gerrit', 'GerritUser')
77                         self.gerritPort = config.get('Gerrit', 'GerritPort')
78                         self.tizenSdkPath = config.get('BuildTools', 'TizenSdkPath')
79                         self.sampleCoreComponentsPath =  config.get('BuildTools', 'SampleCoreComponentsPath')
80                         #ssh://[username@]servername[:port]/
81                         self.gerritSshPrefixUrl = "ssh://"
82                         if self.gerritUser is not None:
83                                 self.gerritSshPrefixUrl += self.gerritUser + "@"
84                         self.gerritSshPrefixUrl += self.gerritServerName
85                         if self.gerritPort is not None:
86                                 self.gerritSshPrefixUrl += ":" + self.gerritPort
87                         self.gerritSshPrefixUrl += "/"
88                         self.nativeSampleProjectList = config.get('Gerrit', 'RepositoryList').split(",")
89                         for i, prj in enumerate(self.nativeSampleProjectList):
90                                 self.nativeSampleProjectList[i] = prj.strip("\n\t")
91                         if os.path.exists(self.tizenSdkPath):
92                                 self.tizenBinary = os.path.join(self.tizenSdkPath, "tools/ide/bin/tizen")
93                         if os.path.exists(self.sampleCoreComponentsPath):
94                                 self.tccBinary = os.path.join(self.sampleCoreComponentsPath, "tool/tcc.py")
95                                 self.convertToSampleProjectBinary = os.path.join(self.sampleCoreComponentsPath, "tool/development/convert-tpk-to-sample-project.sh")
96                                 self.checkpatchTizenBinary = os.path.join(self.sampleCoreComponentsPath, "tool/checkpatch_tizen.pl")
97                         self.emailNotificationsSmtpServerName = config.get('EmailNotifications', 'SmtpServerName')
98                         self.emailNotificationsSmtpPort = int(config.get('EmailNotifications', 'SmtpPort'))
99                         self.emailNotificationsSmtpUser = config.get('EmailNotifications', 'SmtpUser')
100                         self.emailNotificationsSmtpB64EncodedPassword = config.get('EmailNotifications', 'SmtpB64EncodedPassword')
101                         self.emailNotificationsMailFrom = config.get('EmailNotifications', 'MailFrom')
102                         self.emailNotificationsMailTo = config.get('EmailNotifications', 'MailTo').split(",")
103                         self.emailNotificationsMailCc = config.get('EmailNotifications', 'MailCc').split(",")
104                         self.emailNotificationsMailBcc = config.get('EmailNotifications', 'MailBcc').split(",")
105                 else:
106                         raise ValueError('Config file name:' + configFilePath + " does not exist")
107
108 class NativeSample:
109         projectName = None
110         projectPath = None
111         repositoryUrl = None
112         def __init__(self, projectName, projectPath, repositoryUrl):
113                 self.projectName = projectName
114                 self.projectPath = projectPath
115                 self.repositoryUrl = repositoryUrl
116         def __repr__(self):
117                 return  ('NativeSample(projectName: %s, ' \
118                                  'projectPath: %s, '\
119                                  'repositoryUrl = %s)') % (
120                                 self.projectName,
121                                 self.projectPath,
122                                 self.repositoryUrl)
123
124 class NativeSampleChange:
125         revisionId = None
126         changeId = None
127         nativeSample = None
128         def __init__(self, nativeSample, revId, changeId = None):
129                 self.nativeSample = nativeSample
130                 self.revisionId = revId
131                 self.changeId = changeId
132         def __repr__(self):
133                 return  ('NativeSampleChange(nativeSample: %s, ' \
134                                  'revisionId: %s, '\
135                                  'changeId = %s)') % (
136                                 self.nativeSample,
137                                 self.revisionId,
138                                 self.changeId)
139
140 class NativeSamplesDatabase:
141         createDatabaseScript = """
142         CREATE TABLE IF NOT EXISTS changes_to_evaluate (
143                 id INTEGER NOT NULL PRIMARY KEY,
144                 project_name TEXT NOT NULL,
145                 revision_id TEXT NOT NULL
146         );
147         """
148         insertChangeStatement = """
149         INSERT INTO changes_to_evaluate(project_name, revision_id) VALUES(:project_name, :revision_id)
150         """
151         conn = None
152         databaseFile = None
153         def __init__(self, dbfile):
154                 self.databaseFile = dbfile
155                 self.conn = sqlite3.connect(dbfile, isolation_level = None)
156                 self.conn.execute("PRAGMA busy_timeout = 30000")
157                 self.cur = self.conn.cursor()
158                 self.cur.executescript(self.createDatabaseScript)
159                 self.conn.commit()
160         def saveNativeSampleChange(self, nativeSampleChange):
161                 self.cur.execute(self.insertChangeStatement, {'project_name':nativeSampleChange.nativeSample.projectName, 'revision_id': nativeSampleChange.revisionId})
162         def saveNativeSampleChange(self, nativeSampleChange):
163                 self.cur.execute(self.insertChangeStatement, {'project_name':nativeSampleChange.nativeSample.projectName, 'revision_id': nativeSampleChange.revisionId})
164         def deleteNativeSampleChange(self, nativeSampleChange):
165                 self.cur.execute("DELETE FROM changes_to_evaluate WHERE project_name = :project_name AND revision_id = :revision_id", {'project_name':nativeSampleChange.nativeSample.projectName, 'revision_id': nativeSampleChange.revisionId})
166         def getPendingNativeSampleChanges(self, nativeSamples):
167                 ret = []
168                 for row in self.cur.execute("SELECT id, project_name, revision_id FROM changes_to_evaluate ORDER BY id ASC"):
169                         ret.append(NativeSampleChange(NativeSample(row[1], None, None), row[2]))
170                 return ret
171
172 class NativeSampleGerritManager:
173         client = None
174         version = None
175         def __init__(self, config):
176                 self.client = GerritSSHClient(config.gerritServerName, username=config.gerritUser, port = int(config.gerritPort), keepalive=True)
177         def getVersion(self):
178                 return self.client.run_gerrit_command("version").stdout.read()
179         def getChangeInfo(self, nativeSampleChange):
180                 if nativeSampleChange.revisionId is None:
181                         raise ValueError('Native sample revision Id cannot be None for: ' + str(nativeSampleChange))
182                 jsonChangeIdStr = self.client.run_gerrit_command("query --format=JSON --current-patch-set=" + nativeSampleChange.revisionId +" project:" + nativeSampleChange.nativeSample.projectName + " limit:1").stdout.read()
183                 changeInfo = json.loads(jsonChangeIdStr.split("\n")[0])
184                 if 'id' in changeInfo.keys() and 'currentPatchSet' in changeInfo.keys():
185                         return changeInfo
186                 else:
187                         return None
188         def addCommentToChange(self, nativeSampleChange, commentText):
189                 commentText = commentText.replace("'", " ").replace('"', " ")
190                 result = self.client.run_gerrit_command("review -m '\""+commentText+"\"' " + nativeSampleChange.revisionId)
191                 print result.stdout.read(), result.stderr.read()
192
193 class EmailSender:
194         smtpServer = None
195         smtpPort = None
196         smtpUser = None
197         smtpPassword = None
198         mailFrom = None
199         mailTo = None
200         mailCc = None
201         mailBcc = None
202         def __init__(self, config):
203                 self.smtpServer = config.emailNotificationsSmtpServerName
204                 self.smtpPort = config.emailNotificationsSmtpPort
205                 self.smtpUser = config.emailNotificationsSmtpUser
206                 self.smtpPassword = config.emailNotificationsSmtpB64EncodedPassword
207                 self.mailFrom = config.emailNotificationsMailFrom
208                 self.mailTo = config.emailNotificationsMailTo
209                 self.mailCc = config.emailNotificationsMailCc
210                 self.mailBcc = config.emailNotificationsMailBcc
211         def send(self, mailSubject, mailText = None, mailTo = None, mailFrom = None, mailCc = None, mailBcc = None, mimeType = None):
212                 msg = MIMEText(mailText, mimeType or 'plain', 'utf-8')
213                 msg['Subject'] = mailSubject
214                 msg['From'] = self.mailFrom
215                 msg['To'] = ",".join(mailTo or self.mailTo)
216                 msg['CC'] = ",".join(mailCc or self.mailCc)
217                 msg['BCC'] = ",".join(mailBcc or self.mailBcc)
218
219                 s = smtplib.SMTP(host = self.smtpServer, port = self.smtpPort)
220
221                 s.login(self.smtpUser, base64.b64decode(self.smtpPassword))
222                 s.sendmail(msg['From'], msg['To'].split(","), msg.as_string())
223                 s.quit()
224
225 class NativeSamples:
226         #enum like source type
227         SourceTypeSampleProject = 0
228         SourceTypeTpkProject = 1
229         SampleTemplateTypeMobile = 0
230         SampleTemplateTypeWearable = 1
231         SampleTemplateTypeWatchface = 2
232         SampleTemplateTypeService = 3
233         samplesList = []
234         config = None
235         nativeSamplesRootPath = None
236         databaseModel = None
237         gerrit = None
238         emailSender = None
239         def __init__(self, rootBuildPath):
240                 self.nativeSamplesRootPath = rootBuildPath
241                 self.databaseModel = NativeSamplesDatabase(os.path.join(rootBuildPath, ".native-samples.db"))
242                 self.config = NativeSamplesConfig(os.path.join(rootBuildPath, ".native-samples.cfg"))
243                 self.samplesList = self.config.nativeSampleProjectList
244                 self.gerrit = NativeSampleGerritManager(self.config)
245                 self.emailSender = EmailSender(self.config)
246         def _cloneSampleFromGerrit(self, nativeSample):
247                 if os.path.exists(nativeSample.projectPath):
248                         raise ValueError('Path ' + projectPath + ' of project ' + projectName + ' clone already exist')
249                 print "Cloning repository of ", nativeSample
250                 subprocess.check_call(["git", "clone", nativeSample.repositoryUrl, nativeSample.projectPath])
251         def _getNativeSample(self, projectName):
252                 return NativeSample(projectName, os.path.join(self.nativeSamplesRootPath, projectName), self.config.gerritSshPrefixUrl + projectName)
253
254         def pollForChanges(self, projectList = None):
255                 if projectList is None:
256                         projectList = self.samplesList
257                 for nativeSampleProjectName in projectList:
258                         nativeSample = self._getNativeSample(nativeSampleProjectName)
259                         if not os.path.exists(nativeSample.projectPath):
260                                 self._cloneSampleFromGerrit(nativeSample)
261                         gitCommandList = ["git", "--git-dir=" + os.path.join(nativeSample.projectPath, ".git")]
262                         try:
263                                 fetchOutput = subprocess.check_output(gitCommandList + ["fetch", "origin", "refs/changes/*:refs/remotes/origin/gerrit/*"], stderr=subprocess.STDOUT)
264                         except subprocess.CalledProcessError as error:
265                                 if error.returncode != 128:
266                                         print 'network or server error - trying to fetch next project'
267                                 else:
268                                         raise
269                         if len(fetchOutput) > 0:
270                                 print fetchOutput
271                         changeIds = re.findall("(?<=-> ).*", fetchOutput)
272                         if changeIds is None:
273                                 continue
274                         for changeId in changeIds:
275                                 revisionId = subprocess.check_output(gitCommandList + [ "log", "--pretty=format:%H", "-1", changeId])
276                                 self.databaseModel.saveNativeSampleChange(NativeSampleChange(nativeSample, revisionId))
277         def _cleanGitRepo(self, repoDir):
278                 curDir = os.getcwd()
279                 try:
280                         os.chdir(repoDir)
281                         subprocess.call(["git", "checkout", "-q", "."], stderr=subprocess.STDOUT)
282                         subprocess.check_call(["git", "clean", "-fdxq", "."], stderr=subprocess.STDOUT)
283                 finally:
284                         os.chdir(curDir)
285         def _cleanCurrentGitRepo(self):
286                 self._cleanGitRepo(os.getcwd())
287         def _cleanRepoAndCheckoutToRevision(self, sampleChange = None, repoPath = None, revision = None):
288                 curDir = os.getcwd()
289                 try:
290                         os.chdir(repoPath or sampleChange.nativeSample.projectPath or curDir)
291                         self._cleanCurrentGitRepo()
292                         subprocess.check_call(["git", "checkout", "-qf", revision or sampleChange.revisionId])
293                 finally:
294                         os.chdir(curDir)
295         def _sourceType(self, sampleDirectoryPath = None):
296                 curDir = os.getcwd()
297                 try:
298                         if sampleDirectoryPath is not None:
299                                 os.chdir(sampleDirectoryPath)
300
301                         #if sample contains sample.xml then we assume that it is sample project type
302                         if os.path.exists("sample.xml"):
303                                 return self.SourceTypeSampleProject
304                         if os.path.exists("tizen-manifest.xml"):
305                                 return self.SourceTypeTpkProject
306                         raise ValueError("Can't determine source project type in path:" + os.getcwd())
307                 finally:
308                         os.chdir(curDir)
309         def _currentSourceType(self):
310                 return self._sourceType(os.getcwd())
311         def _directoryContainsFileWithString(self, directory, stringToFind):
312                 try:
313                         subprocess.check_call(["grep", "-qr", stringToFind, directory])
314                         return True
315                 except subprocess.CalledProcessError:
316                         return False
317
318         def _sampleTemplateType(self, sampleDirectoryPath = None):
319                 if sampleDirectoryPath is None:
320                         sampleDirectoryPath = os.getcwd()
321                 ret = None
322                 #if it is service type then profile doesn't matter
323                 if self._directoryContainsFileWithString(sampleDirectoryPath, "service_app_lifecycle_callback_s"):
324                         ret = self.SampleTemplateTypeService
325                 elif self._directoryContainsFileWithString(sampleDirectoryPath, "watch_app_lifecycle_callback_s"):
326                         ret = self.SampleTemplateTypeWatchface
327                 if ret is None:
328                         sourceType = self._sourceType()
329                         tizenXmlFilePath = None
330                         descriptionXmlFilePath = None
331                         if sourceType == self.SourceTypeSampleProject:
332                                 descriptionXmlFilePath = os.path.join(os.getcwd(), "description.xml")
333                         elif sourceType == self.SourceTypeTpkProject:
334                                 if not os.path.exists(os.path.join(os.getcwd(), "sample-project-src/description.xml")):
335                                         tizenXmlFilePath = os.path.join(os.getcwd(), "tizen-manifest.xml")
336                                 else:
337                                         descriptionXmlFilePath = os.path.join(os.getcwd(), "sample-project-src/description.xml")
338                         profileType = "undefined"
339                         if descriptionXmlFilePath is not None:
340                                 if not os.path.exists(descriptionXmlFilePath):
341                                         raise ValueError("Can't find description.xml file in %s. Can't determine sample template type." % descriptionXmlFilePath)
342                                 xmlTree = ET.parse(descriptionXmlFilePath)
343                                 xmlRoot = xmlTree.getroot()
344                                 xmlnsPrefix = xmlRoot.tag.replace("Overview", "")
345                                 profileType = xmlRoot.iter(xmlnsPrefix + 'ProfileName').next().text.lower()
346                         if tizenXmlFilePath is not None:
347                                 if not os.path.exists(tizenXmlFilePath):
348                                         raise ValueError("Can't find tizen-manifest.xml file in %s. Can't determine sample template type." % tizenXmlFilePath)
349                                 xmlTree = ET.parse(tizenXmlFilePath)
350                                 xmlRoot = xmlTree.getroot()
351                                 xmlnsPrefix = xmlRoot.tag.replace("manifest", "")
352                                 profileType = xmlRoot.find(xmlnsPrefix + 'profile').attrib["name"]
353
354                         if profileType == "wearable":
355                                 ret = self.SampleTemplateTypeWearable
356                         elif profileType == "mobile":
357                                 ret = self.SampleTemplateTypeMobile
358                 if ret is None:
359                         raise ValueError("Can't determine sample template type")
360                 return ret
361
362         def buildTpk(self):
363                 subprocess.check_call(["rm", "-rf", "Debug"], stderr=subprocess.STDOUT)
364                 try:
365                         output = subprocess.check_output([self.config.tizenBinary, "build-native", "-a", "arm"], stderr=subprocess.STDOUT)
366                         return True, output
367                 except subprocess.CalledProcessError as error:
368                         return False, traceback.format_exc() + "\n" + error.output
369         def buildSampleFromTpkBranch(self, nativeSampleChange, changeInfo = None):
370                 print "========> TPK_BUILD for ", nativeSampleChange.nativeSample.projectName, " and changeId:", nativeSampleChange.changeId
371                 curDir = os.getcwd()
372                 try:
373                         if changeInfo is None:
374                                 changeInfo = self.gerrit.getChangeInfo(nativeSampleChange)
375                         os.chdir(nativeSampleChange.nativeSample.projectPath)
376                         if changeInfo['status'] != "MERGED" and changeInfo['status'] != "ABANDONED":
377                                 if self._currentSourceType() == self.SourceTypeTpkProject:
378                                         print 'building tpk branch'
379
380                                         if os.path.exists(os.path.join(nativeSampleChange.nativeSample.projectPath, "Build")):
381                                                 result, output = self.buildTpk()
382                                                 if result:
383                                                         print output
384                                                         print "SUCCESS: built change " + nativeSampleChange.changeId + " from project " + nativeSampleChange.nativeSample.projectName
385                                                 else:
386                                                         print "ERROR:", output
387                                                         print "FAIL: built change " + nativeSampleChange.changeId + " from project " + nativeSampleChange.nativeSample.projectName
388                                                         return False, output
389                                         else:
390                                                 print 'No Tizen CLI configuration in ' + nativeSampleChange.nativeSample.projectPath
391                                 else:
392                                         print "Can't built for source type other than tpk"
393                         else:
394                                 print "change already " + changeInfo['status']
395                 finally:
396                         os.chdir(curDir)
397                 return True, ""
398         def invokeConvert(self, revision, outputDirectory = None):
399                 if outputDirectory is None:
400                         outputDirectory = os.getcwd()
401                 try:
402                         subprocess.check_call([self.config.convertToSampleProjectBinary, "-v", "-r", revision, "-o", outputDirectory], stderr=subprocess.STDOUT)
403                 except subprocess.CalledProcessError as error:
404                         return False, traceback.format_exc() + "\n" + error.output
405
406         def invokeTcc(self):
407                 templateType = self._sampleTemplateType()
408                 templatePostfix = "undefined"
409                 if templateType == self.SampleTemplateTypeMobile:
410                         templatePostfix = "mobile"
411                 elif templateType == self.SampleTemplateTypeWatchface:
412                         templatePostfix = "watchface"
413                 elif templateType == self.SampleTemplateTypeWearable:
414                         templatePostfix = "wearable"
415                 elif templateType == self.SampleTemplateTypeService:
416                         templatePostfix = "service"
417                 templatePath = os.path.join(self.config.sampleCoreComponentsPath, "rule/" + templatePostfix)
418                 try:
419                         tccOutput = subprocess.check_output([self.config.tccBinary, "-c", templatePath, "."], stderr=subprocess.STDOUT)
420                         result = re.search("[0-9]+(?= code sections are modified)", tccOutput)
421                         if int(result.group(0)) > 0:
422                                 return False, tccOutput
423                         result = re.search("[0-9]+(?= template files are removed)", tccOutput)
424                         if int(result.group(0)) > 0:
425                                 return False, tccOutput
426                 except subprocess.CalledProcessError as error:
427                         return False, traceback.format_exc() + "\n" + error.output
428
429                 return True, tccOutput
430
431
432         def checkSampleUsingTcc(self, nativeSampleChange, changeInfo = None):
433                 print "========> TCC for ", nativeSampleChange.nativeSample.projectName, " and changeId:", nativeSampleChange.changeId
434                 curDir = os.getcwd()
435                 try:
436                         if changeInfo is None:
437                                 changeInfo = self.gerrit.getChangeInfo(nativeSampleChange)
438
439                         if changeInfo['status'] != "MERGED" and changeInfo['status'] != "ABANDONED":
440                                         os.chdir(nativeSampleChange.nativeSample.projectPath)
441                                         self._cleanRepoAndCheckoutToRevision(sampleChange = nativeSampleChange)
442                                         sourceType = self._currentSourceType()
443                                         if sourceType == self.SourceTypeTpkProject:
444                                                 tempTccOutputDir = tempfile.mkdtemp()
445                                                 self.invokeConvert(revision = nativeSampleChange.revisionId, outputDirectory = tempTccOutputDir)
446                                                 os.chdir(tempTccOutputDir)
447                                         elif sourceType != self.SourceTypeSampleProject:
448                                                 raise ValueError("Wrong source type to use tcc tool")
449                                         result, tccOutput = self.invokeTcc()
450                                         print tccOutput
451                                         if not result:
452                                                 print 'FAIL: tcc for ', nativeSampleChange.nativeSample.projectName, ' and changeId:', nativeSampleChange.changeId
453                                                 return False, tccOutput
454                         else:
455                                 print "change already " + changeInfo['status']
456                 finally:
457                         self._cleanRepoAndCheckoutToRevision(sampleChange = nativeSampleChange)
458                         os.chdir(curDir)
459                 print 'SUCCCESS: tcc for ', nativeSampleChange.nativeSample.projectName, ' and changeId:', nativeSampleChange.changeId
460                 return True, ""
461         def invokeCheckpatchTizen(self):
462                 try:
463                         filesToCheck = []
464                         for root, dirs, files in os.walk(os.getcwd()):
465                                 for fileName in files:
466                                         if fileName.endswith(".c") or fileName.endswith(".h"):
467                                                 filesToCheck.append(os.path.join(root, fileName))
468                         checkPatchTizenOutput = subprocess.check_output(["perl", self.config.checkpatchTizenBinary] + filesToCheck, stderr=subprocess.STDOUT)
469                         return True, checkPatchTizenOutput
470                 except subprocess.CalledProcessError as err:
471                         return False, traceback.format_exc()
472
473         def checkSampleUsingCheckpatchTizen(self, nativeSampleChange, changeInfo):
474                 print "========> CHECKPATCH_TIZEN for ", nativeSampleChange.nativeSample.projectName, " and changeId:", nativeSampleChange.changeId
475                 curDir = os.getcwd()
476                 try:
477                         if changeInfo is None:
478                                 changeInfo = self.gerrit.getChangeInfo(nativeSampleChange)
479
480                         if changeInfo['status'] != "MERGED" and changeInfo['status'] != "ABANDONED":
481                                 os.chdir(nativeSampleChange.nativeSample.projectPath)
482                                 self._cleanRepoAndCheckoutToRevision(sampleChange = nativeSampleChange)
483                                 res, output = self.invokeCheckpatchTizen()
484                                 if res:
485                                         print output
486                                         print "SUCCESS: sources checked with checkpatch_tizen.pl for " + nativeSampleChange.changeId + " from project " + nativeSampleChange.nativeSample.projectName
487                                 else:
488                                         print "ERROR:", output
489                                         print "FAIL: sources checked failed with checkpatch_tizen.pl for " + nativeSampleChange.changeId + " from project " + nativeSampleChange.nativeSample.projectName
490                                         return False, output
491                         else:
492                                 print "change already " + changeInfo['status']
493                 finally:
494                         self._cleanRepoAndCheckoutToRevision(sampleChange = nativeSampleChange)
495                         os.chdir(curDir)
496                 return True, ""
497         def evaluateChange(self, nativeSampleChange):
498                 print 'evaluating change:', nativeSampleChange
499                 curDir = os.getcwd()
500                 os.chdir(nativeSampleChange.nativeSample.projectPath)
501
502                 self._cleanRepoAndCheckoutToRevision(sampleChange = nativeSampleChange)
503                 changeInfo = self.gerrit.getChangeInfo(nativeSampleChange)
504
505                 if changeInfo is not None:
506                         if changeInfo['status'] != "MERGED" and changeInfo['status'] != "ABANDONED":
507                                 nativeSampleChange.changeId = changeInfo['id']
508
509                                 result, message = self.buildSampleFromTpkBranch(nativeSampleChange, changeInfo)
510                                 if result:
511                                         self.gerrit.addCommentToChange(nativeSampleChange, "BuildBot: Compilation successful")
512                                 else:
513                                         self.gerrit.addCommentToChange(nativeSampleChange, "BuildBot: Compilation Failed:"+message)
514
515                                 result, message = self.checkSampleUsingTcc(nativeSampleChange, changeInfo)
516                                 if result:
517                                         self.gerrit.addCommentToChange(nativeSampleChange, "BuildBot: TCC Check successful")
518                                 else:
519                                         self.gerrit.addCommentToChange(nativeSampleChange, "BuildBot: TCC Check Failed:"+message)
520
521                                 result, message = self.checkSampleUsingCheckpatchTizen(nativeSampleChange, changeInfo)
522                                 if result:
523                                         self.gerrit.addCommentToChange(nativeSampleChange, "BuildBot: checkpatch_tizen successful")
524                                 else:
525                                         self.gerrit.addCommentToChange(nativeSampleChange, "BuildBot: checkpatch_tizen Failed:"+message)
526                         else:
527                                 print "Change already " + changeInfo['status']
528                 else:
529                         subject = "Can't find change id for change with revision : " + nativeSampleChange.revisionId + " of project:" + nativeSampleChange.nativeSample.projectName
530                         print subject
531                         self.emailSender.send(mailSubject = subject)
532                 os.chdir(curDir)
533
534         def evaluateProject(self, nativeSample):
535                 print "evaluating project", nativeSample.projectName
536                 curDir = os.getcwd()
537                 def convertResult(resultList):
538                         ret = {'result': False, 'comment': None}
539                         ret['result'] = resultList[0]
540                         print resultList[1]
541                         if resultList[0]:
542                                 ret['comment'] = "OK"
543                         else:
544                                 ret['comment'] = resultList[1]
545                         return ret
546                 try:
547                         os.chdir(nativeSample.projectPath)
548                         subprocess.call(["git", "fetch", "origin"], stderr=subprocess.STDOUT)
549                         self._cleanRepoAndCheckoutToRevision(repoPath = nativeSample.projectPath, revision="origin/tpk")
550
551                         #now we are on tpk branch - let's get first change
552                         ret = {
553                                 'TPK_BUILD': {'result': False, 'comment': None},
554                                 'TCC_CHECK': {'result': False, 'comment': None},
555                                 'CHECKPATCH_TIZEN': {'result': False, 'comment': None}
556                                 }
557
558                         print '=======> TPK_BUILD for ', nativeSample.projectName
559
560                         ret["TPK_BUILD"] = convertResult(self.buildTpk())
561
562                         print '=======> CHECKPATCH_TIZEN ', nativeSample.projectName
563                         ret["CHECKPATCH_TIZEN"] = convertResult(self.invokeCheckpatchTizen())
564
565                         self._cleanCurrentGitRepo()
566                         tempTccOutputDir = tempfile.mkdtemp()
567                         self.invokeConvert(revision = "origin/tpk", outputDirectory = tempTccOutputDir)
568                         os.chdir(tempTccOutputDir)
569                         print '=======> invoking TCC_CHECK ', nativeSample.projectName
570                         ret["TCC_CHECK"] = convertResult(self.invokeTcc())
571
572                 finally:
573                         os.chdir(curDir)
574                 return ret
575         def evaluatePendingChanges(self):
576                 changesList = self.databaseModel.getPendingNativeSampleChanges(self)
577
578                 for i in range(len(changesList)):
579                         try:
580                                 changesList[i].nativeSample = self._getNativeSample(changesList[i].nativeSample.projectName)
581                                 self.evaluateChange(changesList[i])
582                                 self.databaseModel.deleteNativeSampleChange(changesList[i])
583                         except KeyboardInterrupt:
584                                 raise
585                         except:
586                                 subject = 'Tizen SAMPLE BUILD SYSTEM error: Something unexpected happened during build process'
587                                 stacktrace = "Exception Info:\n\n" + traceback.format_exc()
588                                 traceback.print_exc()
589                                 self.emailSender.send(mailSubject = subject, mailText = stacktrace)
590                                 print "Evaluating next change"
591         def dailyRegressionCheck(self):
592                 htmlText = "<HTML><TABLE border=\"1\" style=\"width:80%\"><TR><TH>Project Name</TH><TH>Check step</TH><TH>Result</TH><TH>Comment</TH></TR>"
593                 for sampleProjectName in self.samplesList:
594                         try:
595                                 nativeSample = self._getNativeSample(sampleProjectName)
596                                 if not os.path.exists(nativeSample.projectPath):
597                                         self._cloneSampleFromGerrit(nativeSample)
598                                 res = self.evaluateProject(nativeSample)
599                                 spanText = "<TD rowspan=\"3\">%s</TD>" % sampleProjectName
600                                 res.keys().sort()
601                                 for i, checkStep in enumerate(res.keys()):
602                                         htmlText += "<TR>"
603                                         if i == 0:
604                                                 htmlText += spanText
605                                         htmlText += ("<TD>%s</TD><TD>%i</TD><TD>%s</TD></TR>") % (checkStep, res[checkStep]['result'], res[checkStep]['comment'].replace("\n", "<br>"))
606                         except KeyboardInterrupt:
607                                 raise
608                         except:
609                                 subject = 'Tizen DAILY REGRESSION BUILD SYSTEM error: Something unexpected happened during daily build process'
610                                 stacktrace = "Exception Info:\n\n" + traceback.format_exc()
611                                 traceback.print_exc()
612                                 self.emailSender.send(mailSubject = subject, mailText = stacktrace)
613                                 print "Evaluating next project"
614                 self.emailSender.send(mailSubject = 'DAILY REGRESSION TESTS SUMMARY (' + str(datetime.date.today())+")", mailText = htmlText, mimeType='html')
615                 htmlText += "</TABLE></HTML>"