Dataset Viewer
Auto-converted to Parquet
blob_id
stringlengths
40
40
language
stringclasses
1 value
text
stringlengths
7
63.2k
index_in_file
int64
0
3
d786e89b9d478dcff3c541c89731247075d078c3
Python
''' @author: Ken Venner @contact: [email protected] @version: 1.13 Read in a file of wine names and create consistent wine descriptions from these names. ''' import kvutil import kvcsv import re import sys import shutil # may comment out in the future import pprint pp = pprint.PrettyPrinter(indent=4) ppFlag = False # application variables optiondictconfig = { 'AppVersion' : { 'value' : '1.13', 'description' : 'defines the version number for the app', }, 'debug' : { 'value' : False, 'type' : 'bool', 'description' : 'defines if we are running in debug mode', }, 'verbose' : { 'value' : 1, 'type' : 'int', 'description' : 'defines the display level for print messages', }, 'setup_check' : { 'value' : False, 'type' : 'bool', 'description' : 'defines if we checking out setup', }, 'pprint' : { 'value' : False, 'type' : 'bool', 'description' : 'defines if we output with pretty print when debugging', }, 'csvfile_master_in' : { 'value' : 'wine_xref.csv', 'description' : 'defines the name of the master data input file', }, 'csvfile_update_in' : { 'value' : 'wineref.csv', 'description' : 'defines the name of the input file to updated', }, 'csvfile_update_out' : { 'value' : 'wineref2.csv', 'description' : 'defines the name of the updated output file', }, 'fldWine' : { 'value' : 'wine', 'description' : 'defines the name of the field that holds the Wine ', }, 'fldWineDescr' : { 'value' : 'winedescr', 'description' : 'defines the name of the field holding the wine description', }, 'fldWineDescrNew' : { 'value' : 'winedescrnew', 'description' : 'defines the name of the NEW field holding the new description ', }, 'fldWineDescrMatch' : { 'value' : None, 'description' : 'defines the name of the NEW field holding the results of comparison existing to new description ', }, 'fldWineMaster' : { 'value' : None, 'description' : 'defines the name of the field that holds the Wine when reading the master file ', }, 'fldWineDescrMaster' : { 'value' : None, 'description' : 'defines the name of the field holding the wine description when reading the master file', }, 'backupfile_ext' : { 'value' : '.bak', 'description' : 'defines the extension to use to copy the update input file to if we are replacing it with output', }, 'defaultnew' : { 'value' : None, 'description' : 'defines if we should take field fldWineDescrNew and set to a value if not set', }, } ### GLOBAL VARIABLES / LOOKUPS ######################################## # regex search for vintage in wine name vintageLookup = ( re.compile('\d\d\d\d\s+\d\d(\d\d)'), # two years together - get this one over early re.compile('^\d\d(\d\d)'), # four position start of line re.compile('\s\d\d(\d\d)$'), # four position end of line re.compile('\s\d\d(\d\d)\s'), # four position middle of line re.compile('XX\d\d(\d\d)\s'), # four position middle of line re.compile('\s\d\d(\d\d)\/'), # four position split re.compile('\s\'?(\d\d)\'?$|\s\'?(\d\d)\'?\s'), # two position date with optional apostrophe front or back ) # regex search for case in wine name reCase = re.compile(r'12\s*X\s*750\s*ML|\bcase\b|12\/750\s*ML',re.IGNORECASE) # regex to pick up qualifiers from the wine reQualLookup = ( (None, re.compile(r'\bWithout\s+Gift\b|\bNo\s+Gift', re.IGNORECASE)), # the none gift do them first ('Gift', re.compile(r'\bGift\b', re.IGNORECASE)), ('VAP', re.compile(r'\bVAP\b', re.IGNORECASE)), ('VAP', re.compile(r'\bGlassVAP\b', re.IGNORECASE)), ('Glass', re.compile(r'\bGlass\b', re.IGNORECASE)), ('Glass', re.compile(r'\bGlasses\b', re.IGNORECASE)), ('Etch', re.compile(r'\bEtch\b', re.IGNORECASE)), ('Basket', re.compile(r'\bBasket\b', re.IGNORECASE)), ) # regex search to define the size of the wine bottle sizeLookup = ( ('1.75L', re.compile(r'\b1\.75\s*Li?|\b1\.75$', re.IGNORECASE)), ('1.5L', re.compile(r'\b1\.5\s*L?\b|\bMagnum\b', re.IGNORECASE)), ('375mL', re.compile(r'Half\s+Bottle|375ml', re.IGNORECASE)), ('200mL', re.compile(r'\b200\s*ML|\(200\s*ML', re.IGNORECASE)), ('50mL', re.compile(r'\b50\s*ML|\(50\s*ML', re.IGNORECASE)), ('500mL', re.compile(r'\b500\s*ML|\(500\s*ML', re.IGNORECASE)), ('3L', re.compile(r'\b3\s*Li?', re.IGNORECASE)), ('6L', re.compile(r'\b6\s*Li?', re.IGNORECASE)), ('9L', re.compile(r'\b9\s*Li?', re.IGNORECASE)), ('1L', re.compile(r'\b1L\b|\b1\s+L$|\b1.0\s*L\b|\b1\s+Liter\b|\bOne\s+Liter\b|\bLITER\b|\b1\s*LTR', re.IGNORECASE)), ) # regex extract winery names from the wine field wineryLookup = ( ('Alban', re.compile(r'\bAlban\b', re.IGNORECASE)), ('Arrowood', re.compile(r'\bArrowood\b', re.IGNORECASE)), ('Atalon', re.compile(r'\bAtalon\b', re.IGNORECASE)), ('Attune', re.compile(r'\bAttune\b', re.IGNORECASE)), ('Auteur', re.compile(r'\bAuteur\b', re.IGNORECASE)), ('Austin Hope', re.compile(r'\bAustin\s+Hope\b', re.IGNORECASE)), ('Badge', re.compile(r'\bBadge\b', re.IGNORECASE)), ('Balletto', re.compile(r'\bBalletto\b', re.IGNORECASE)), ('Bell', re.compile(r'\bBell\s+Cellar', re.IGNORECASE)), ('BR Cohn', re.compile(r'\bB\.?\s?R\.?\s+Cohn\b', re.IGNORECASE)), ('Bremer', re.compile(r'\bBremer\b', re.IGNORECASE)), ('Brewer-Clifton', re.compile(r'\bBrewer[\s\-]Clifton\b', re.IGNORECASE)), ('BV', re.compile(r'\bBeaulieu\s+V|\bBV\b', re.IGNORECASE)), ('Belle Glos', re.compile(r'\bBelle\s+Glos\b', re.IGNORECASE)), ('Bennett Ln', re.compile(r'\bBennet+\sLane\b', re.IGNORECASE)), ('Benovia', re.compile(r'\bBenovia\b', re.IGNORECASE)), ('Beringer', re.compile(r'\bBeringer\b', re.IGNORECASE)), ('Blackstone', re.compile(r'\bBlackstone\b', re.IGNORECASE)), ('Brancott', re.compile(r'\bBrancott\b', re.IGNORECASE)), ('Cade', re.compile(r'\bCade\b', re.IGNORECASE)), ('Cain Five', re.compile(r'\bCain\s+Five\b|\bCain\s-\sFive\b|\bCain\s5\b|\bCainFive\b', re.IGNORECASE)), ('Cakebread', re.compile(r'\bCakebread\b', re.IGNORECASE)), ('Cardinale', re.compile(r'\bCardinale\b', re.IGNORECASE)), ('Caymus', re.compile(r'\bCaymus\b', re.IGNORECASE)), ('Chappellet', re.compile(r'\bChappellet\b', re.IGNORECASE)), ('Chalk Hill', re.compile(r'\bChalk\s+Hill\b', re.IGNORECASE)), ('Clos Du Bois', re.compile(r'\bClos\s+Du\s+Bois\b', re.IGNORECASE)), ('ClosDuVal', re.compile(r'\bClos\s+du\s+Val\b', re.IGNORECASE)), ('Colgin', re.compile(r'\bColgin\b', re.IGNORECASE)), ('Concha Don Melchor', re.compile(r'\bConcha\s.*Don\s+Melchor\b|Don\s+Melchor\b', re.IGNORECASE)), ('Continuum', re.compile(r'\bContinuum\b', re.IGNORECASE)), ('Corison', re.compile(r'\bCorison\b', re.IGNORECASE)), ('Cristal', re.compile(r'Roederer\s?.*Cristal\b|\bCristal\b.+Brut', re.IGNORECASE)), ('Curran', re.compile(r'\bCurran\b', re.IGNORECASE)), ('Darioush', re.compile(r'\bDarioush\b', re.IGNORECASE)), ('Darioush', re.compile(r'\bCaravan\b', re.IGNORECASE)), ('David Arthur', re.compile(r'\bDavid\s+Arthur\b', re.IGNORECASE)), ('David Bruce', re.compile(r'\bDavid\s+Bruce\b', re.IGNORECASE)), ('Davis Family', re.compile(r'\bDavis\s+Family\b', re.IGNORECASE)), ('Del Dotto', re.compile(r'\bDel\s+Dotto\b', re.IGNORECASE)), ('Dominus', re.compile(r'\bDominus\b', re.IGNORECASE)), ('Goldeneye', re.compile(r'\bGoldeneye\b', re.IGNORECASE)), # before duckhorn ('Paraduxx', re.compile(r'\bParaduxx\b', re.IGNORECASE)), # before duckhorn ('Domaine Carneros', re.compile(r'\bDomaine\s+Carneros\b', re.IGNORECASE)), ('Dominus', re.compile(r'\Dominus\b', re.IGNORECASE)), ('Drappier', re.compile(r'\bDrappier\b', re.IGNORECASE)), ('Duckhorn', re.compile(r'\bDuckhorn\b', re.IGNORECASE)), ('Dumol', re.compile(r'\bDumol\b', re.IGNORECASE)), ('Dunn', re.compile(r'\bDunn\b', re.IGNORECASE)), ('Ehlers', re.compile(r'\bEhlers\b', re.IGNORECASE)), ('Etude', re.compile(r'\bEtude\b', re.IGNORECASE)), ('Far Niente', re.compile(r'\bFar Niente\b', re.IGNORECASE)), ('Flora', re.compile(r'\bFlora\s+Springs\b', re.IGNORECASE)), ('Flowers', re.compile(r'\bFlowers\b', re.IGNORECASE)), ('Robert Foley', re.compile(r'\bRobert\s+\bFoley\b', re.IGNORECASE)), #before Foley ('Foley', re.compile(r'\bFoley\b', re.IGNORECASE)), ('Foxen', re.compile(r'\bFoxen\b', re.IGNORECASE)), ('Franciscan', re.compile(r'\bFranciscan\b', re.IGNORECASE)), ('Frank Family', re.compile(r'\bFrank Family\b', re.IGNORECASE)), ('Gary Farrell', re.compile(r'\bGary\s+Farrel+\b', re.IGNORECASE)), ('Ghost Block', re.compile(r'\bGhost\s+Block\b', re.IGNORECASE)), ('Grgich', re.compile(r'\bGrgich\b', re.IGNORECASE)), ('Groth', re.compile(r'\bGroth\b', re.IGNORECASE)), ('Gundlach', re.compile(r'\bGundlach\b', re.IGNORECASE)), ('Hansel', re.compile(r'\bHansel\b', re.IGNORECASE)), ('Hanzell', re.compile(r'\bHanzell\b', re.IGNORECASE)), ('Hess', re.compile(r'\bHess\b', re.IGNORECASE)), ('Hewitt', re.compile(r'\bHewitt\b', re.IGNORECASE)), ('Hobbs', re.compile(r'\bHobbs\b|\bcrossbarn\b', re.IGNORECASE)), ('Hundred Acre', re.compile(r'\bHundred\s+Acre\b', re.IGNORECASE)), ('Jordan', re.compile(r'\bJordan\b', re.IGNORECASE)), ('Justin', re.compile(r'\bJustin\b', re.IGNORECASE)), ('Kim Crawford', re.compile(r'\bKim\s+Crawford\b', re.IGNORECASE)), ('Kistler', re.compile(r'\bKistler\b', re.IGNORECASE)), ('Kosta', re.compile(r'\bKosta\s+Browne?\b', re.IGNORECASE)), ('Krug', re.compile(r'\bKrug\b', re.IGNORECASE)), ('Kunde', re.compile(r'\bKunde\b', re.IGNORECASE)), ('LaCrema', re.compile(r'\bLa\s?Crema\b', re.IGNORECASE)), ('Lewis', re.compile(r'\bLewis\b', re.IGNORECASE)), ('Lokoya', re.compile(r'\bLokoya\b', re.IGNORECASE)), ('Meiomi', re.compile(r'\bMeiomi\b', re.IGNORECASE)), ('Melville', re.compile(r'\bMelville\b', re.IGNORECASE)), ('Momento Mori', re.compile(r'\bMomento\s+Mori\b', re.IGNORECASE)), ('Mondavi', re.compile(r'\bMondavi\b', re.IGNORECASE)), ('Montelena', re.compile(r'\bMontelena\b', re.IGNORECASE)), ('Mt Veeder', re.compile(r'^Mount\s+Veeder\b|^Mt\.? Veeder\b|\d+\s+M[^t]*t\s+Veeder\b', re.IGNORECASE)), ('Newton', re.compile(r'\bNewton\b', re.IGNORECASE)), ('Nickel', re.compile(r'\bNickel\b', re.IGNORECASE)), ('Opus One', re.compile(r'\bOpus\s+One\b', re.IGNORECASE)), ('P Togni', re.compile(r'\bTogni\b', re.IGNORECASE)), ('Pahlmeyer Jayson', re.compile(r'\bJayson\b', re.IGNORECASE)), # this before pahlmeyer ('Pahlmeyer', re.compile(r'\bPahlmeyer\b(?!\s*Jay)', re.IGNORECASE)), ('Papillon', re.compile(r'\bPapillon\b', re.IGNORECASE)), ('Patz', re.compile(r'\bPatz\b', re.IGNORECASE)), ('Phelps', re.compile(r'\bPhelps\b', re.IGNORECASE)), ('Plumpjack', re.compile(r'\bPlumpjack\b', re.IGNORECASE)), ('Pride', re.compile(r'\bPride\b', re.IGNORECASE)), ('Prisoner', re.compile(r'\bPrisoner\b', re.IGNORECASE)), ('Provenance', re.compile(r'\bProvenance\b', re.IGNORECASE)), ('R Sinskey', re.compile(r'\bSinskey\b', re.IGNORECASE)), ('Ramey', re.compile(r'\bRamey\b', re.IGNORECASE)), ('Revana', re.compile(r'\bRevana\b', re.IGNORECASE)), ('Raptor', re.compile(r'\bRaptor\s+Ridge\b', re.IGNORECASE)), ('Revana', re.compile(r'\bRevana\b', re.IGNORECASE)), ('Ridge', re.compile(r'\bRidge\b', re.IGNORECASE)), ('Robert Foley', re.compile(r'\bRobert\s+Foley\b', re.IGNORECASE)), ('Rombauer', re.compile(r'\bRombauer\b', re.IGNORECASE)), ('Rudd', re.compile(r'\bRudd\b', re.IGNORECASE)), ('Scarecrow', re.compile(r'\bScarecrow\b', re.IGNORECASE)), ('Sea Smoke', re.compile(r'\bSea\s+Smoke\b', re.IGNORECASE)), ('Seghesio', re.compile(r'\bSeghesio\b', re.IGNORECASE)), ('Shafer', re.compile(r'\bShafer\b', re.IGNORECASE)), ('Sherwin', re.compile(r'\bSherwin\b', re.IGNORECASE)), ('Silver Oak', re.compile(r'\bSilver\s+Oak\b', re.IGNORECASE)), ('Silverado', re.compile(r'\bSilverado\b', re.IGNORECASE)), ('Simi', re.compile(r'\bSimi\b', re.IGNORECASE)), ('Sonoma Cutrer', re.compile(r'\bCutrer\b', re.IGNORECASE)), ('Spottswoode', re.compile(r'\bSpottswoode\b', re.IGNORECASE)), ('Stag Leap', re.compile(r'\bStag.*\sLeap\b', re.IGNORECASE)), ('Sullivan', re.compile(r'\bSullivan\b', re.IGNORECASE)), ('Summerland', re.compile(r'\bSummerland\b', re.IGNORECASE)), ('Summers', re.compile(r'\bSummers\b', re.IGNORECASE)), ('Tantara', re.compile(r'\bTantara\b', re.IGNORECASE)), ('Turnbull', re.compile(r'\bTurnbull\b', re.IGNORECASE)), ('Veuve', re.compile(r'\bVeuve\b', re.IGNORECASE)), ('Viader', re.compile(r'\bViader\b', re.IGNORECASE)), ('Waterstone', re.compile(r'\bWaterstone\b', re.IGNORECASE)), ('Whitehall', re.compile(r'\bWhitehall\b', re.IGNORECASE)), ('Wm Selyem', re.compile(r'\bWilliams\s*\-?Selyem\b', re.IGNORECASE)), ('ZD', re.compile(r'\bZD\b', re.IGNORECASE)), ('Zaca', re.compile(r'\bZaca\b', re.IGNORECASE)), ('zBourbon Woodford Res', re.compile(r'\bWoodford\s+Reserve\b', re.IGNORECASE)), ('zBourbon Woodford Res', re.compile(r'\bWoodford\s+Rsv\b', re.IGNORECASE)), ('zCognac Courvoisier', re.compile(r'\bCourvoisier\b', re.IGNORECASE)), ('zCognac Hennessy', re.compile(r'\bHennesse?y\b', re.IGNORECASE)), ('zCognac Remy', re.compile(r'\bRemy\s+Martin\b|\bRemy\s+Louis', re.IGNORECASE)), ('zCointreau', re.compile(r'\bCointreau\b', re.IGNORECASE)), ('zGin Hendrick', re.compile(r'\bHendrick', re.IGNORECASE)), ('zGin Tanqueray', re.compile(r'\bTanqueray\b', re.IGNORECASE)), ('zRum Mt Gay', re.compile(r'\bMount\s+Gay\b|\bMt\s+Gay', re.IGNORECASE)), ('zRum Ron Zacapa', re.compile(r'\bRon\s+Zacapa\b', re.IGNORECASE)), ('zRye Hayden', re.compile(r'\bBasil\s+Hayden\b', re.IGNORECASE)), ('zSambuca', re.compile(r'\bSambuca\b', re.IGNORECASE)), ('zScotch Glenmorangie', re.compile(r'\bGlenmorangie\b', re.IGNORECASE)), ('zScotch Hibiki Harmony', re.compile(r'\bHibiki\s.*Harmony\b', re.IGNORECASE)), ('zScotch Hibiki', re.compile(r'\bHibiki\b(?!\s*Har)', re.IGNORECASE)), ('zScotch Macallan', re.compile(r'\bMacallan\b', re.IGNORECASE)), ('zTeq Campo Azul', re.compile(r'\bCampo\s+Azul\b', re.IGNORECASE)), ('zTeq Casamigos', re.compile(r'\bCasamigos\b', re.IGNORECASE)), ('zTeq Casino Azul', re.compile(r'\bCasino\s+Azul\b', re.IGNORECASE)), ('zTeq Clase Azul', re.compile(r'\bClase\s+Azul\b', re.IGNORECASE)), ('zTeq Cuervo', re.compile(r'\bJose\s+Cuervo\b|^Cuervo\b', re.IGNORECASE)), ('zTeq Don Julio', re.compile(r'\bDon\s+Julio\b', re.IGNORECASE)), ('zTeq Dos Artes', re.compile(r'\bDos\s+Artes\b|^Cuervo\b', re.IGNORECASE)), ('zTeq Gran Cava', re.compile(r'\bGran\s+Cava\b', re.IGNORECASE)), ('zTeq Herradura', re.compile(r'\bHerradura\b', re.IGNORECASE)), ('zTeq Loma Azul', re.compile(r'\bLoma\s+Azul\b', re.IGNORECASE)), ('zTeq Padre Azul', re.compile(r'\bPadre\s+Azul\b', re.IGNORECASE)), ('zTeq Partida', re.compile(r'\bPartida\b', re.IGNORECASE)), ('zTeq Patron', re.compile(r'\bPatron\b', re.IGNORECASE)), ('zTripleSec Gr Marnier', re.compile(r'\bGrand\s+Marnier\b', re.IGNORECASE)), ('zTripleSec Dekuyper', re.compile(r'\bDekuyper\b', re.IGNORECASE)), ('zTripleSec Hiram', re.compile(r'\bHiram\b', re.IGNORECASE)), ('zVodka Absolut', re.compile(r'\bAbsolut\b', re.IGNORECASE)), ('zVodka Skyy', re.compile(r'\bSkyy\b', re.IGNORECASE)), ('zVodka Tito', re.compile(r'\bTito', re.IGNORECASE)), ('zWhiskey Balvenie', re.compile(r'\bBalvenie\b', re.IGNORECASE)), ('zWhiskey J Walker', re.compile(r'\bJohn+ie\s+Walker\b', re.IGNORECASE)), # ('', re.compile(r'\b\b', re.IGNORECASE)), ) # regex extract the grape from the wine fld grapeLookup = ( ('Cab Franc', re.compile(r'\bCabernet\s+Franc|\bCab\s+Franc', re.IGNORECASE)), # before cab ('Cab', re.compile(r'\bCabernet\b|\sCS\s|\sCS$|\bCab\b', re.IGNORECASE)), ('Claret', re.compile(r'\bClaret\b', re.IGNORECASE)), ('Rose Pinot', re.compile(r'\bRose\b.*\bPinot\b|\bPinot\b.*\bRose\b', re.IGNORECASE)), ('Pinot', re.compile(r'\bPinot\b|\bPN\b|\bP\s+Noir\b', re.IGNORECASE)), ('Merlot', re.compile(r'\bMerlot\b|\bME\b', re.IGNORECASE)), ('Sauv Blanc', re.compile(r'\bSauvignon\s+Blanc\b|\bSB\b', re.IGNORECASE)), ('Sauv Blanc', re.compile(r'\bSauvignon\/Fume\s+Blanc\b', re.IGNORECASE)), ('Meritage', re.compile(r'\bMeritage\b', re.IGNORECASE)), ('Fume', re.compile(r'\bFume\b|\bFumé', re.IGNORECASE)), ('Champagne', re.compile(r'\bChampagne\b', re.IGNORECASE)), ('Chard', re.compile(r'\bChar+d|\bCH\b', re.IGNORECASE)), ('Shiraz', re.compile(r'\bShiraz\b', re.IGNORECASE)), ('Syrah', re.compile(r'\bSyrah\b|\bSY\b',re.IGNORECASE)), ('Zin', re.compile(r'\bZinfandel\b|\bZIN\b|\bZN\b', re.IGNORECASE)), ('Rose', re.compile(r'\bRose\b|\bRosé', re.IGNORECASE)), ('Sangiovese', re.compile(r'\Sangiovese\b', re.IGNORECASE)), # ('Brandy', re.compile(r'\bBrandy\b', re.IGNORECASE)), ('Gewurzt', re.compile(r'\bGew.rztraminer\b|\bGewürzt', re.IGNORECASE)), ('Malbec', re.compile(r'\bMalbec\b', re.IGNORECASE)), ('Viognier', re.compile(r'\bViognier\b', re.IGNORECASE)), ('Roussanne', re.compile(r'\bRoussanne\b', re.IGNORECASE)), ('Charbono', re.compile(r'\bCharbono\b', re.IGNORECASE)), ('PSirah', re.compile(r'\bPetite Sirah\b', re.IGNORECASE)), ('Cuvee', re.compile(r'\bCuvee\b', re.IGNORECASE)), ('Red', re.compile(r'\bRed\b|\bBordeaux\s+Blend\b', re.IGNORECASE)), ('Syrah-Cab', re.compile(r'\bSyrcab\b|\bsyrah[-\s\/]+cab', re.IGNORECASE)), ('Grenache', re.compile(r'\bGrenache\b', re.IGNORECASE)), ('Tempranillo', re.compile(r'\bTempranillo\b', re.IGNORECASE)), ) # wineries that we don't want to look up the grape on ignoreGrapeLookup = { 'Cristal' : ['Rose', None], 'Domaine Carneros' : ['Brut', None], 'Dominus' : [None], 'Papillon' : None, 'Paraduxx' : None, 'Veuve' : None, 'zCointreau' : None, 'zGin Hendrick' : None, 'zGin Tanqueray' : ['Ten', None], 'zTripleSec Gr Marnier' : ['1880', '100th', 'Cent', 'Quin', None], 'zTripleSec Dekuyper' : None, 'zTripleSec Hiram' : None, 'zVodka Skyy' : ['Citrus', None], 'zVodka Tito' : None, # 'Prisoner' : ['Cuttings', 'Red', 'Derange', 'Saldo', 'Blindfold', None], } # winery to wine lookup when no grape is found in the wine name # # extract the wine name from a winery - when a field does not have a grape lookup for the row # the name looked up and found will be the name used noGrapeLookup = { 'Ehlers' : ['120-80'], # matches an abbreviations - and matches fldWineDescr 'Alban' : ['Pandora'], 'BV' : ['Tapestry', 'Latour'], 'Bennett Ln' : ['Maximus'], 'Bremer' : ['Austintatious'], 'Cain Five' : None, 'Colgin' : ['Cariad', 'IX'], 'Concha Don Melchor' : None, 'Continuum' : None, 'Darioush' : ['Duel', 'Darius'], 'Duckhorn' : ['Discussion'], 'Far Niente' : ['Dolce'], 'Flora' : ['Trilogy'], 'Franciscan' : ['Magnificat'], 'Grgich' : ['Violetta'], 'Gundlach' : ['Vintage Reserve'], 'Justin' : ['Isosceles'], 'Krug' : ['Generations'], 'Mondavi' : ['Maestro'], 'Newton' : ['Puzzle'], 'Opus One' : None, 'Phelps' : ['Insignia'], 'Prisoner' : ['Cuttings', 'Derange', 'Saldo', 'Blindfold'], 'Ridge' : ['Monte Bello'], 'Robert Foley' : ['Griffin'], 'Sullivan' : ['Coeur de Vigne'], 'Zaca' : ['ZThree', 'ZCuvee'], 'zCognac Courvoisier' : ['Napolean', 'VS', 'VSOP', 'XO'], 'zCognac Hennessy' : ['Paradis', 'Richard', 'VS', 'VSOP', 'XO', 'Master'], 'zCognac Remy' : ['1738', 'Louis XIII', 'VSOP', 'XO', 'VS'], 'zRum Ron Zacapa' : ['23', 'Negra', 'XO'], 'zRye Hayden' : ['Dark', 'Caribbean'], 'zScotch Hibiki Harmony' : None, # 'zScotch Hibiki' : ['Toki', '12', '17', '21', '30'], 'zTeq Campo Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], 'zTeq Casamigos' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], 'zTeq Casino Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado', 'Silver'], 'zTeq Clase Azul' : ['Ultra', 'Extra Anejo', 'Anejo', 'Blanco', 'Reposado', 'Mezcal', 'Plata', 'Platino'], 'zTeq Dos Artes' : ['Extra Anejo'], 'zTeq Gran Cava' : ['Extra Anejo'], 'zTeq Loma Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], # 'zTeq Padre Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], 'zTeq Partida' : ['Blanco', 'Elegante'], 'zVodka Absolut' : ['Citron', 'Mandarin', 'Mandrin', 'Mango', 'Ruby', 'Vanilia', 'Raspberri', 'Grapevine', None], 'zWhiskey J Walker' : ['Double Black', 'Black', 'Blue', 'Gold', 'Green', 'Platinum', 'Red','Swing', 'White', '18', '21'], } # regex to use to determine if this is a liquor not a wine # # winery -> [ liquor, regex ] # if there is no grape, and no noGrapeLookup found, but the winery has a liquorLookup # use the list of lookups to find the additional infomratoin to add to the winery # liquorLookup = { 'zRum Mt Gay' : [ ('1703 Mst', re.compile(r'\b1703\b', re.IGNORECASE)), ('BB', re.compile(r'\bBlack Barrel\b', re.IGNORECASE)), ('Eclipse Silver', re.compile(r'\bEclipse\s+Silver\b', re.IGNORECASE)), ('Eclipse', re.compile(r'\bEclipse\b', re.IGNORECASE)), ('Old Peat', re.compile(r'\bOld Peat', re.IGNORECASE)), ('Old Pot', re.compile(r'\bPot\s+Still\b', re.IGNORECASE)), ('Old', re.compile(r'\bOld\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ('XO Peat', re.compile(r'\bXO\b', re.IGNORECASE)), ], 'zScotch Glenmorangie' : [ ('10', re.compile(r'\b10(YR)?\b', re.IGNORECASE)), ('14 Port', re.compile(r'14.+\bQuinta\b|14.+\bPort\b|\bQuinta\b.+14|\bPort\b.+14', re.IGNORECASE)), ('12 Bacalta', re.compile(r'\bBacalta\b', re.IGNORECASE)), ('12 Burgundy', re.compile(r'\bBurgundy\b', re.IGNORECASE)), ('12 Nectar', re.compile(r'\bNectar\b', re.IGNORECASE)), ('12 Port', re.compile(r'\bQuinta\b|\bPort\b', re.IGNORECASE)), ('12 Sherry', re.compile(r'\bLa\s?Santa\b|\bSherry\b', re.IGNORECASE)), ('12 Signet', re.compile(r'\bSignet\b', re.IGNORECASE)), ('15 Cadboll', re.compile(r'\bCadboll', re.IGNORECASE)), ('15', re.compile(r'\b15(YR)?\b', re.IGNORECASE)), ('18', re.compile(r'\b18(YR)?\b|\b18YEAR\b', re.IGNORECASE)), ('25 Astar', re.compile(r'\bAstar\b', re.IGNORECASE)), ('25', re.compile(r'\b25(YR)?\b', re.IGNORECASE)), ('Companta', re.compile(r'\bCompanta\b', re.IGNORECASE)), ('Finealta', re.compile(r'\bFinealta\b', re.IGNORECASE)), ('Milsean', re.compile(r'\bMilsean\b', re.IGNORECASE)), ('Sonnalta', re.compile(r'\bSonnalta\b', re.IGNORECASE)), ], 'zScotch Macallan' : [ ('10 Fine', re.compile(r'\bFine.*\b10\b|\b10.*Fine')), ('10', re.compile(r'\b10\b')), ('12 Double Gold', re.compile(r'\bDbl\b.*Gold|\bDouble\b.*Gold', re.IGNORECASE)), ('12 Double', re.compile(r'\bDouble\s.*12(YR)?\b', re.IGNORECASE)), ('12 Double', re.compile(r'\b12\s.*Double\b', re.IGNORECASE)), ('12 Double', re.compile(r'\bDbl\b|\bDouble\b', re.IGNORECASE)), ('12 Edition 1', re.compile(r'\bEdition\s.*1\b', re.IGNORECASE)), ('12 Edition 2', re.compile(r'\bEdition\s.*2\b', re.IGNORECASE)), ('12 Edition 3', re.compile(r'\bEdition\s.*3\b', re.IGNORECASE)), ('12 Edition 4', re.compile(r'\bEdition\s.*4\b', re.IGNORECASE)), ('12 Sherry', re.compile(r'\b12\s.*Sherry\b|\bSherry\b\s.*\b12', re.IGNORECASE)), ('12 Triple', re.compile(r'\b12(YR)?\s.*Triple\b', re.IGNORECASE)), ('12 Triple', re.compile(r'\bTriple\s.*12\b', re.IGNORECASE)), ('12', re.compile(r'\b12(YR)?\b', re.IGNORECASE)), ('15 Triple', re.compile(r'\b15(YR)?\s.*Triple\b|Triple.+\b15(YR)?\b', re.IGNORECASE)), ('15 Fine', re.compile(r'\b15(YR)?\b.*\bFine\b', re.IGNORECASE)), ('15', re.compile(r'\b15(YR)?\b', re.IGNORECASE)), ('17 Sherry', re.compile(r'\b17(YR)?\s.*Sherry\b', re.IGNORECASE)), ('17 Fine', re.compile(r'\b17(YR)?\b.*\bFine\b', re.IGNORECASE)), ('17', re.compile(r'\b17(YR)?\b', re.IGNORECASE)), ('18 Sherry', re.compile(r'\b18(YR)?\s.*Sherry\b|Sherry\b.*18', re.IGNORECASE)), ('18 Triple', re.compile(r'\b18(YR)?\s.*Triple\b|Triple.+\b18(YR)?\b', re.IGNORECASE)), ('18 Fine', re.compile(r'\b18(YR)?\b.*\bFine\b', re.IGNORECASE)), ('18 Gran', re.compile(r'Gran\b.*\b18', re.IGNORECASE)), ('18', re.compile(r'\b18(YR)?\b', re.IGNORECASE)), ('21 Fine', re.compile(r'\b21.*Fine\b', re.IGNORECASE)), ('21', re.compile(r'\b21(YR)?\b', re.IGNORECASE)), ('25 Sherry', re.compile(r'\b25\s.*Sherry\b', re.IGNORECASE)), ('25', re.compile(r'\b25(YR)?\b')), ('30 Sherry', re.compile(r'\b30\s.*Sherry', re.IGNORECASE)), ('30 Triple', re.compile(r'\b30(YR)?\s.*Triple\b|Triple.+\b30(YR)?\b', re.IGNORECASE)), ('30 Fine', re.compile(r'\b30(YR)?\b.*\bFine\b|Fine.*30', re.IGNORECASE)), ('30', re.compile(r'\b30(YR)?\b')), ('Rare', re.compile(r'\bRare\b', re.IGNORECASE)), ], 'zTeq Cuervo' : [ ('Especial Gold', re.compile(r'\bEspecial\b.*Gold\b|Gold.*Especial', re.IGNORECASE)), ('Especial Blue', re.compile(r'\bEspecial\b.*Blue\b', re.IGNORECASE)), ('Especial', re.compile(r'\bEspecial\b', re.IGNORECASE)), ('Familia Platino', re.compile(r'\bPlatino\b', re.IGNORECASE)), ('Familia Anejo', re.compile(r'\bFamilia\b|\bReserva\b', re.IGNORECASE)), ('Gold', re.compile(r'\bGold\b', re.IGNORECASE)), ('Reposado Lagavulin', re.compile(r'\bReposado.*Lagavulin', re.IGNORECASE)), ('Tradicional Anejo', re.compile(r'Tradicional.*Anejo|Anejo.*Tradicional', re.IGNORECASE)), ('Tradicional Reposado', re.compile(r'Tradicional.*Reposado|Reposado.*Tradicional', re.IGNORECASE)), ('Tradicional Silver', re.compile(r'\bTradicional\b', re.IGNORECASE)), ('Tradicional Silver', re.compile(r'\bTraditional\b', re.IGNORECASE)), ('Reposado', re.compile(r'\bReposado\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ], 'zTeq Don Julio' : [ ('1942', re.compile(r'\b1942\b', re.IGNORECASE)), ('Real', re.compile(r'\bReal\b', re.IGNORECASE)), ('Anejo Claro 70th', re.compile(r'\b70th\b', re.IGNORECASE)), ('Anejo Claro', re.compile(r'\bAnejo\b\s*Claro\b', re.IGNORECASE)), ('Anejo', re.compile(r'\bAnejo\b', re.IGNORECASE)), ('Blanco', re.compile(r'\bBlanco\b', re.IGNORECASE)), ('Reposado Lagavulin', re.compile(r'\bRepo.+Lagvulin\b', re.IGNORECASE)), ('Reposado Dbl', re.compile(r'\bReposado.+Double\b', re.IGNORECASE)), ('Reposado Dbl', re.compile(r'\bReposado.+Dbl\b', re.IGNORECASE)), ('Reposado Dbl', re.compile(r'\bDouble.+Reposado\b', re.IGNORECASE)), ('Reposado Private', re.compile(r'\bReposado.+Private\b', re.IGNORECASE)), ('Reposado', re.compile(r'\bReposado\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ], 'zTeq Herradura' : [ ('Ultra', re.compile(r'\bUltra\b', re.IGNORECASE)), ('Suprema', re.compile(r'\bSuprema\b', re.IGNORECASE)), ('Anejo', re.compile(r'\bAnejo\b', re.IGNORECASE)), ('Blanco', re.compile(r'\bBlanco\b', re.IGNORECASE)), ('Reposado Gold', re.compile(r'\bReposado\s+Gold\b|\bGold\s+Reposado\b', re.IGNORECASE)), ('Reposado Scotch', re.compile(r'\bReposado.+Scotch\b|\bScotch.+Reposado\b', re.IGNORECASE)), ('Reposado Port', re.compile(r'\bPort.+Reposado\b|\bReposado.+Port\b', re.IGNORECASE)), ('Reposado', re.compile(r'\bReposado\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ], 'zTeq Patron' : [ ('Gran Piedra', re.compile(r'\bPiedra\b', re.IGNORECASE)), ('DELETE Roca DELETE', re.compile(r'\bRoca\b', re.IGNORECASE)), ('Anejo Extra Lalique', re.compile(r'\bLalique\b', re.IGNORECASE)), ('Anejo Extra 7yr', re.compile(r'\b7YR\b|\b7 anos\b|\b7 year\b', re.IGNORECASE)), ('Anejo Extra 5yr', re.compile(r'\b5YR\b|\b5 anos\b|\b5 year\b', re.IGNORECASE)), ('Anejo Extra 10yr', re.compile(r'\b10\b.+\bExtra\b|\bExtra\b.+10', re.IGNORECASE)), ('Anejo Extra', re.compile(r'\bExtra\s+Anejo\b', re.IGNORECASE)), ('Gran Anejo', re.compile(r'\bGran\s+Anejo\b', re.IGNORECASE)), ('Gran Anejo', re.compile(r'\bBurdeos\b', re.IGNORECASE)), ('Gran Smoky', re.compile(r'\bGran\s+.*Smoky\b', re.IGNORECASE)), ('Anejo', re.compile(r'\bAnejo\b', re.IGNORECASE)), ('Gran Platinum', re.compile(r'\bPlatinum\b', re.IGNORECASE)), ('Reposado', re.compile(r'\bReposado\b', re.IGNORECASE)), ('Silver LTD', re.compile(r'\bSilver.*Limited\b|\bLimited.*Silver\b', re.IGNORECASE)), ('Silver Estate', re.compile(r'\bEstate.*Silver\b|\bSilver.*Estate\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ('Blanco', re.compile(r'\bBlanco\b', re.IGNORECASE)), # ('', re.compile(r'\b\b', re.IGNORECASE)), ], 'zTeq Padre Azul' : [ ('Blanco', re.compile(r'\bsilver\b', re.IGNORECASE)), ], 'zWhiskey Balvenie' : [ ('12 Double', re.compile(r'\bDouble.*12(YR)?\b', re.IGNORECASE)), ('12 Double', re.compile(r'\b12(YR)?\s.*Double', re.IGNORECASE)), ('12 First', re.compile(r'\b12(YR)?\s.*First', re.IGNORECASE)), ('12 USA', re.compile(r'\b12.*American|American.*12', re.IGNORECASE)), ('12 Toast', re.compile(r'\b12(YR)?\s.*Toast', re.IGNORECASE)), ('12', re.compile(r'\b12(YR)?\b', re.IGNORECASE)), ('14 Carib', re.compile(r'\b14(YR)?\s.*Carib', re.IGNORECASE)), ('14 Carib', re.compile(r'\b14(YR)?\s.*CB\s+Cask', re.IGNORECASE)), ('14 Carib', re.compile(r'\bCarr?ib', re.IGNORECASE)), ('14 Peat', re.compile(r'\b14(YR)?\s.*Peat', re.IGNORECASE)), ('15 Sherry', re.compile(r'\b15(YR)?\s.*Sherry\b', re.IGNORECASE)), ('15 Sherry', re.compile(r'\bSherry\s+.*15(YR)?\b', re.IGNORECASE)), ('15', re.compile(r'\b15(YR)?\b', re.IGNORECASE)), ('16 Triple', re.compile(r'\b16(YR)?\s.*Triple\b', re.IGNORECASE)), ('17 Sherry Double', re.compile(r'\b17(YR)?\s.*Sherry\s+Doub', re.IGNORECASE)), ('17 Sherry', re.compile(r'\b17(YR)?\s.*Sherry', re.IGNORECASE)), ('17 Double', re.compile(r'\b17(YR)?\s.*Double', re.IGNORECASE)), ('17 Double', re.compile(r'\bDouble.*17(YR)?\b', re.IGNORECASE)), # 17 Double Sherry # 17 Islay # 17 New Oak ('17 Peat', re.compile(r'\b17(YR)?\s.*Peat', re.IGNORECASE)), ('17 Peat', re.compile(r'\bPeat.*17(YR)?\b', re.IGNORECASE)), ('17', re.compile(r'\b17(YR)?\b', re.IGNORECASE)), ('21 Port', re.compile(r'\b21.*Port', re.IGNORECASE)), ('21 Port', re.compile(r'\bPort.*21\b', re.IGNORECASE)), ('21', re.compile(r'21', re.IGNORECASE)), ('25', re.compile(r'\b25(YR)?\b', re.IGNORECASE)), ('30', re.compile(r'\b30(YR)?\b', re.IGNORECASE)), ('40', re.compile(r'\b40(YR)?\b', re.IGNORECASE)), ], 'zBourbon Woodford Res' : [ ('Dbl', re.compile(r'\bDouble\b', re.IGNORECASE)), ('Derby', re.compile(r'\bDerby\b', re.IGNORECASE)), ('Rye Choc', re.compile(r'\bChocolate.*Rye\b', re.IGNORECASE)), ('Rye', re.compile(r'\bRye\b', re.IGNORECASE)), ('Brandy', re.compile(r'\bBrandy\b', re.IGNORECASE)), ('Batch', re.compile(r'\bBatch\b', re.IGNORECASE)), ('Barrel', re.compile(r'\bBarrel\b', re.IGNORECASE)), ('Master', re.compile(r'\bMasters?\b', re.IGNORECASE)), ('Malt', re.compile(r'\bMalt\b', re.IGNORECASE)), ('Maple', re.compile(r'\bMaple\b', re.IGNORECASE)), ('Wheat', re.compile(r'\bWheat\b', re.IGNORECASE)), ('', re.compile(r'\bWoodford\b', re.IGNORECASE)), ], 'zSambuca' : [ ('Romana Black', re.compile(r'\bRomana.*\bBlack\b|\bBlack\s+Romana\b', re.IGNORECASE)), ('Romana', re.compile(r'\bRomana\b', re.IGNORECASE)), ('Di Amore', re.compile(r'\bdi Amore\b', re.IGNORECASE)), ], 'zScotch Hibiki' : [ ('12', re.compile(r'\b12\s*YE?A?R\b', re.IGNORECASE)), ('17 Limited', re.compile(r'\b17\s*YE?A?R\b.+Limited', re.IGNORECASE)), ('17', re.compile(r'\b17\s*YE?A?R\b', re.IGNORECASE)), ('21 Limited', re.compile(r'\b21\s*YE?A?R\b.+Limited', re.IGNORECASE)), ('21', re.compile(r'\b21\s*YE?A?R\b', re.IGNORECASE)), ('30', re.compile(r'\b30\s*YE?A?R\b', re.IGNORECASE)), ] } # regex to expand out optional values in the optoinal values to find a match against wine fld wineAbbrLookup = { '120-80' : r'\bOne\s+Twenty\s+Over\s+Eighty\b', '3Amigos' : r'\bThree\s+Amigos\b', '3Palms' : r'\bThree\s+Palms\b', '3Sister' : r'\bThree\s+Sisters?\b', '4Barrell' : r'\b4[\-\s]Barrels?\b', 'Alex' : r'\bAlexander\b', 'And' : r'\bAnderson\b', 'Car' : r'\bCarneros\b', 'Carries' : r'\bCarrie', 'CC' : r'\bC\.?C\.?\s+Ranch\b', 'Clone4' : r'\bClone\s+4\b', 'Clone6' : r'\bClone\s+6\b', 'Crossbarn' : r'\bCross\s+Barn\b', 'Donna' : r'\bDonna', 'Est' : r'\bEstate\b', 'Estate' : r'\bEst\b', 'Gap' : r'\bGap|\s%27Gap', 'Gary' : r'\bGary', 'Julia' : r'\bJulia', 'Knights' : r'\bKnight', 'KistlerVnyd' : r'\bKistler (Vineyard|VYD|EST)\b', 'LP' : r'\bLes Pierres\b', 'Lyn' : r'\bLyndenhur?st\b', 'Mont' : r'\bMonterey\b', 'Mt' : r'\bMount\b|\bMt\.\b', 'Napa/Son' : r'\bNapa.*Son', 'Oak' : r'\bOakville\b', 'One-Pt-5' : r'\bOne\s+Point\s+Five\b', 'Pomm' : r'\bPommeraie\b', 'Priv' : r'\bPrivate\b', 'RR' : r'\bRussian\s+Rivers?\b|RRV', 'RRR' : r'\bRussian\s+Rivers?\b|RRV', 'Res' : r'\bReserve\b|\bRsv\b|\bResrv\b|\bReserv\b|\bReserve$', 'Rose' : r'\bRosé|\bROSÉ|\bRos%E9', 'Ruth' : r'\bRutherford\b', 'Sandy' : r'\bSandy', 'Samanthas' : r'\bSamantha', 'SC' : r'\bSanta\s+Cruz\b', 'SLD' : r'\bStag.*Leap\b', 'SLH' : r'\bSanta\s+Lucia\b', 'SMV' : r'\bSanta\s+Maria|\bS\s+Maria', 'SRH' : r'\bSTA\.?|\bSANTA\s+Rita\b|\bSTA\sRITA\sHILLS|\bS\s+RITA\b', 'SS' : r'\bSpecial\s+\Selection\b', 'Stage' : r'\bStagecoach\b', 'Son' : r'\bSonoma\b', 'SYV' : r'\bSanta\s+Ynez\s+Valley\b', 'TD9' : r'\bTD\s+9\b|\bTD-9\b', 'Terraces' : r'\bTerrace', 'TheCutrer' : r'\bThe Cutrer\b|nnay Cutrer\b', 'Tok' : r'\bTo[\s\-]?Kolan|\bTo[\s\-]?Kalon', 'Turn4' : r'\bTurn\s+4\b', 'Vernas' : r'\bVerna', 'Vine' : r'\bVines\b', 'Yount' : r'\bYountville\b', 'ZThree' : r'\bZ.*\bThree\b', 'ZCuvee' : r'\bZ.*\bCuvee\b|\bCuvee Z\b', # misspellings 'Agustina' : r'\bAugustina\b', 'Durell' : r'\bDurrell\b', 'Bench
0
d786e89b9d478dcff3c541c89731247075d078c3
Python
land' : r'\bBenchlands\b', 'Pritchard' : r'\bPitchard\b', } # regex search - set the ships as reShipsAs = re.compile(r'\(ships?\s', re.IGNORECASE) # the order in which we pull multiple single match attributes defaultorderlist=[['Tok'], ['Oak'], ['Res'], ['RR'], ['Landslide'], ['Yount'], ['RRR'], ['Son'], ['Ruth'], ['Napa'], ['Helena'], ['SRH'], ['SLH'], ['SMV'], ['SLD'], ['Paso'], ['Alex'], ['Single'], ['Estate']] ### FUNCTIONS ############################################ ######################################################################################### def globalVariableCheck( debug=False ): # check for liquor definitions that are in noGrapeLookup # these will never execute for liquor in liquorLookup: if liquor in noGrapeLookup: print('WARNING:liquorLookup regexs will never execute - they are in noGrapeLookup:', liquor) if liquor in ignoreGrapeLookup: print('WARNING:liquorLookup regexs will never execute - they are in ignoreGrapeLookup:', liquor) for winery in ignoreGrapeLookup: if winery in noGrapeLookup: print('WARNING:ignoreGrapeLookup regexs will never execute - they are in noGrapeLookup:', winery) ######################################################################################### def setOptionDictMasterFldValues( optiondict, debug=False ): # default these fields to the fld values if they are not set # otherwise leave them alone for fld in ('fldWine', 'fldWineDescr'): if not optiondict[fld+'Master']: optiondict[fld+'Master'] = optiondict[fld] ######################################################################################### # having a list of names to look at and match on - see if this record has a match # nameLookup - list of names could have 'None' as the last value, or just the value of None # lookupStr - string to be searched # other - array of strings that will have the matching name removed from # msg - string defining who called this function # # returns: string - if a matching string is found # None - did not find a match # '' - valid match with "None" # def wineLookupByName( nameLookup, lookupStr, other, msg, wineAbbrLookup=None, debug=False ): # string for debugging messages funcname = 'wineLookupByName:' + msg + ':' # debugging if debug: print(funcname + 'nameLookup:', nameLookup) # if the value for this winery is None - than there is no additiona work we are done if nameLookup is None: # no additional processing # debugging if debug: print(funcname + 'match: value is none - continue on') # return empty string return '' # there are additional lookups for this winery - not using grape as part of the description # check each of the things to look up for name in nameLookup: # debugging if debug: print(funcname + 'match-name:', name) # special processing of a lookup value of none if name is None: # Lookup on none - means just use what we found # debugging if debug: print(funcname + 'name-matched: value is none - continue on:pass back blank') # stop iterating on nameLookup - by returning empty string return '' # we have not encountered 'None' - so build the regex based on the text provided reName = re.compile( r'\b'+name+r'\b', re.IGNORECASE) # check to see if we have a match with this regex if reName.search(lookupStr): # we have a match - so this is the additional attribute we are looking for # debugging if debug: print(funcname+'name-MATCHED:', name) # remove from other if it is in there for val in other: if reName.search(val): other.remove(val) # debugging if debug: print(funcname + 'name-remove-from-other:', val) # stop iterating on nameLookup - return what we found return name # 2nd check see if have a translation and this name is translatable if wineAbbrLookup and name in wineAbbrLookup: # build the regex with the look up value reName = re.compile(wineAbbrLookup[name], re.IGNORECASE) # debugging if debug: print(funcname + 'Abbr-match-name:', name) # check to see if we have a match with this regext if reName.search(lookupStr): # we have a match - so this is the additional attribute we are looking for # debugging if debug: print(funcname+'Abbr-name-MATCHED:', wineAbbrLookup[name]) # remove from other if it is in there for val in other: if reName.search(val): other.remove(val) # debugging if debug: print(funcname + 'name-remove-from-other:', val) # stop iterating on nameLookup - return what we found return name # checked all the namelookupd - and did not find any matches # debuging if debug: print(funcname + 'name match not found:set to blank') # return none meaning we did not find a match return None ######################################################################################### # find the qualifer like gift, etch, glass tied to this string # # # # returns: first qualifier or None # def findQualifier( wine, debug=False ): for (val, reSearch) in reQualLookup: if reSearch.search(wine): if debug: print('findQualifier:matched-returning:', val) return val if debug: print('findQualifier:no-match-returning:', None) return None ######################################################################################### # find the winery tied to the rec # # Global Variable Used: wineryLookup (an array of regex that define the winery) # # returns: (winery, reWinery) # def findWinery( rec, lastWinery, lastReWinery, fldWine, debug=False ): # if we had a prior winery - test for this match first if lastWinery: # debugging if debug: try: print('fw:new winery:', rec[fldWine]) except Exception as e: print('debug error8-continuing:', str(e)) print('rec[fldWine]:type:', type(rec[fldWine])) # print('fw:new winery:', rec[fldWine].decode('windows-1252')) print('fw:checking if this is lastWinery:', lastWinery) # check to see if the winery is a match again for this record if lastReWinery.search(rec[fldWine]): # debugging if debug: print('fw:this matches the last winery') # match again - return values return(lastWinery, lastReWinery) else: # not match - debugging if debug: print('fw:not last winery') # if we did not match lastWinery - lets look through the list # go through the list of wineries (global variable), # each row contains wineryName, wineryRegex # pulling out the tuple from the lookup for (winery, reWinery) in wineryLookup: # debugging if debug: print('fw:not lastWinery-checking winery:', winery) if fldWine not in rec: print('not a column in this record fldWine:', fldWine) print('rec:', rec) # check to see if this winery is a match if reWinery.search(rec[fldWine]): # debugging if debug: print('fw:winery match found:', winery) # this is a match - set the variables return (winery, reWinery) # for loop ends without a match # did not find a matching winery in the for loop - clear values return (None, None) ######################################################################################### # find the liquor tied to the rec, leveraging the winery # Global Variable Used: liquorLookup # # returns: (liquor, reLiquor) # def findLiquor( rec, winery, fldWine, debug=False ): # go through the list of liquors (global variable), pulling out the tuple from the lookup for (liquor, reLiquor) in liquorLookup[winery]: # debugging if debug: print('fl:checking liquor:', liquor) # check to see if this liquor is a match if reLiquor.search(rec[fldWine]): # debugging if debug: print('fl:liquor match found:', liquor) # this is a match - set the variables return (liquor, reLiquor) # for loop ends without a match # did not find a matching liquor in the for loop - clear values return (None, None) ######################################################################################### # find the grape tied to the rec by regex evaluation # # Global Variable Used: grapeLookup # # returns: (grape, reGrape) # def findGrapeByRegex( rec, fldWine, debug=False ): # go through the list of liquors (global variable), pulling out the tuple from the lookup for (grape, reGrape) in grapeLookup: # debugging if debug: print('fgbr:grape:', grape) # check to see if this liquor is a match if grape is not None and reGrape.search(rec[fldWine]): # debugging if debug: print('fgbr:grape match found:', grape) # this is a match - set the variables return (grape, reGrape) # for loop ends without a match # did not find a matching grape in the for loop - clear values return (None, None) ######################################################################################### # find a string in a field of a record using string match and # on match, return that it matched and the remainder of the string as an array # # returns: (findStr, other) # def findStrInRecReturnOther( rec, fldWineDescr, findStr, debug=False ): # find where in the string this findStr is positioned matchLoc = rec[fldWineDescr].find(findStr) # if we found a location if matchLoc > -1: # then strip everthing to the left of the findStr value and then split this to create other attributes other = rec[fldWineDescr][matchLoc+len(findStr)+1:].split() # debugging if debug: print('fsirro:findStr matched:', findStr) if debug: print('fsirro:findStr other:', other) # return what we found return (findStr, other) #no match found - debugging if debug: print('fsirro:findStr did not match using:', findStr) # did not find a matching findStr - return that fact return (None, []) ######################################################################################### # find the grape tied to the rec and the list of other attributes # to the right of the grape in that description # # Global Variable Used: grapeLookup # # returns: (grape, other) # def findGrapeByStr( rec, fldWineDescr, debug=False ): # find the grape and strip everything right of that from the fldWineDescr field for (grape,reGrape) in grapeLookup: # debugging if debug: print('fg:grape:', grape) # find where in the string this grape is positioned (grape, other) = findStrInRecReturnOther( rec, fldWineDescr, grape, debug=debug) # if we have a match return that match if grape: return (grape, other) # did not find a matching grape - return that fact return (None, []) ######################################################################################### # find the vintage tied to the rec # # Global Variable Used: vintageLookup # # returns: vintage # def findVintage( rec, fldWine, debug=False ): # loop through the vintage lookup records for reVintage in vintageLookup: # search for match m = reVintage.search(rec[fldWine]) # if there is a match if m: # extract the vlaue from the first regex group with a value if m.group(1): vintage = m.group(1) if debug: print('fv:vintage-match:', reVintage,':group1') elif m.group(2): vintage = m.group(2) if debug: print('fv:vintage-match:', reVintage,':group2') elif m.group(3): vintage = m.group(3) if debug: print('fv:vintage-match:', reVintage,':group3') else: vintage = m.group(4) if debug: print('fv:vintage-match:', reVintage,':group4') # return what we vound return vintage # did not find it return None ######################################################################################### # Create the winery/grape-wine-liquour conversion table based on the # array of records passed in # # this routine takes the already read in list of definitions and parses them up # in order to create a winery-wine-attributes file - that will be used # later to take new records from searching the internet and properly assign # an aligned/consistent wine description to that wine string # # we expect the wines array to have attributes: fldWineDescr (winedescr), and fldWine (wine_name) # # returns: wgLookup - dictionary - which is built from parsing winedescr NOT wine_name # # wgLookup[winery][grape] = list of lists of attributes to perform lookups with # def buildWineryGrapeLookup( wines, fldWineDescr='winedescr', fldWine='wine', debug=False ): # local variables wgLookup = {} lastWinery = None lastReWinery = None # step through the records read in for rec in wines: # debugging if debug: print('bwgl:new rec:', rec[fldWineDescr]) # set the variable if not fldWineDescr in rec: print('creating-field:', fldWineDescr) rec[fldWineDescr] = '' # local loop variables winery = grape = wine = liquor = None other = [] ### WINERY (lastWinery, lastReWinery) = (winery, reWinery) = findWinery( rec, lastWinery, lastReWinery, fldWine, debug=debug ) # if we did not find the winery - skipt this record if not winery: # debugging if debug: print('bwgl:did not find winery-skipping:', rec[fldWine]) # don't process this record - get the next record to process continue ### IGNOREGRAPE and NOGRAPE and LIQUOR # if this winery has a noGrapeLookup option - use that to split up the record if winery in ignoreGrapeLookup: ### BLANK WINE # don't get the grape for this winery # set wine to blank wine = '' # debugging if debug: print('bwgl:wine check ignoreGrapeLookup on winery:', winery) elif winery in noGrapeLookup: ### NO GRAPE WINE -- fldWineDescr # debugging if debug: print('bwgl:wine check noGrapeLookup on winery:', winery) # find which wine is a match from the noGrapeLookup wine = wineLookupByName( noGrapeLookup[winery], rec[fldWineDescr], [], 'noGrapeLookup', debug=debug ) # not getting a match - we want to continue to have the wine as blank if False and wine == '': # debugging if debug: print('bwgl:nograpelookup:no-match:set wine to None') wine = None elif winery in liquorLookup: ### LIQUOR ---- fldWine # debugging if debug: print('bwgl:liquor check on winery:', winery) # see if a liquor matches (liquor, reLiquor) = findLiquor( rec, winery, fldWine, debug=debug ) # if we found match - populate wine so we don't look for grape if liquor is not None: wine = liquor # debugging if debug: print('bwgl:liquor found and put in wine:', wine) ### GRAPE (if we have not filled in wine) --- fldWineDescr if wine is None: # debugging if debug: print('bwgl:grape check because wine is None') # determine if there is a grape in this string # if ther (grape,other) = findGrapeByStr( rec, fldWineDescr ) # debugging if debug: print('bwgl:grape:', grape, ':other:', other) else: # debugging if debug: print('bwgl:grape check skipped - we have a wine') ### Skip this record if we don't have a wine or a grape if wine is None and grape is None: # debugging if debug: print('bwgl:record skipped - no grape or wine defined') continue ### OTHER (if not already created by grape lookup) ---- fldWineDescr # # if we did not find the grape in the string # so other was not populated # we need to look up other using 'winery' as the filter if grape is None: # debugging if debug: print('bwgl:build other from winery') # find where in the string this grape is positioned (wineryFind, other) = findStrInRecReturnOther( rec, fldWineDescr, winery, debug=debug) ### OTHER Additional Processing # remove CASE - the keyword case if it exists if 'case' in other: other.remove('case') # debugging if debug: print('bwgl:remove case from other') # remove VINTAGE and/or BOTTLESIZE and/or other QUALIFIERS # the last element will either be the vintage (no bottle size) # or will be the bottle size and then next is the vintage # if the last position is not vintage, attempt to remove the bottle size # then remove vintage - this should be the vintage (validated by isdigit lookup) if other: if debug: print('bwgl:looking at other for quals, bottlesize and vintage') # remove qualifiers if exist if not other[-1].isdigit(): # first we check to see if there is a qualifier appended # we are not vintage as the position posiition - see if it is size for qual,reQual in reQualLookup: if qual == other[-1]: if debug: print('bwgl:remove qualifier from other:', qual) del other[-1] break # remove bottle size if exist if other and not other[-1].isdigit(): # we are not vintage as the position posiition - see if it is size for size,reSize in sizeLookup: if size == other[-1]: if debug: print('bwgl:remove bottlesize from other:', size) del other[-1] break # remove vintage if it is there if other and other[-1].isdigit(): # first check to see if this is part of the ignore grape solution if winery in ignoreGrapeLookup and ignoreGrapeLookup[winery]and other[-1] in ignoreGrapeLookup[winery]: if debug: print('bwgl:value is in ignoreLookupGrape - keeping it:', other[-1]) else: # debugging if debug: print('bwgl:remove vintage from other:', other[-1]) del other[-1] # remove WINE - the element if the element is the same as the wine if wine and wine in other: other.remove(wine) # debugging if debug: print('bwgl:remove wine from other:', wine) # debugging if debug: try: print('bwgl:Final-Build:', winery, ':', grape, ':', wine, ':', liquor, ':', other, ':', rec[fldWineDescr], ':', rec[fldWine]) except Exception as e: print('debug error2-continuing:', str(e)) print('fldWine:', fldWine) ### BUILD LOOKUP FOR CONVERSION (we use the grape attribute to build the dictionary) # move liquor value into grape because we did not find the if grape is None and wine is not None: grape = wine # debugging if debug: print('bwgl:set-grape-to-wine:', grape) ### WINERY:GRAPE-WINE-LIQOUR Dictionary creation # debugging if debug: print('bwgl:create wgLookup for winery:', winery, ':grape:', grape) # validate we have an entry for this winery in the lookup dict if winery not in wgLookup: # one does not create - so create a stub for winery:grape wgLookup[winery] = { grape : [] } else: # one DOES exist - check to see if the grape is already here if grape not in wgLookup[winery]: # grape is not here - so create an empty list to stuff values into wgLookup[winery][grape] = [] # check to see if we have OTHER attributes # and if we do - check to see that this list of attributes # is not already in the wineLookup array # and if this list does not exist - then append this list if other and other not in wgLookup[winery][grape]: # add this list of other to this entry wgLookup[winery][grape].append(other) # debugging if debug: print('bwgl:appending to wgLookup:other:', other) # end loop on wines ### SORTED WINERY:GRAPE lookup - most optional attributes first in the list # debbuging if debug: print('bwgl:complete-read-of-master-file:sort wgLookup') # now sort the list of lookups from most specific (greatest number of attributes) to least for winery in wgLookup: for grape in wgLookup[winery]: wgLookup[winery][grape] = sorted(wgLookup[winery][grape], key=len, reverse=True) # debugging if debug: print('\n'*5) print('START WGLOOKUP DUMPED') print('#'*80) if ppFlag: pp.pprint(wgLookup) else: print('bwgl:final-wgLookup:\n', wgLookup) print('#'*80) # done with for loop - return the lookup return wgLookup ######################################################################################### # find the matching set of additional attributes that match this record # from the global lookup. # # we assume that we have already tested that winery and value exist in wgLookup prior to calling this routine # # the special paramaters here are: # value - this is either "wine" or "grape" - this routine allows you to lookup on different attributes # valueDescr - passed in string for debugging telling us which value was passed in # # defaultorderlist = array of array of string - gives the default order of singlematch looks to determine which of # many matches is the one we will select # # Global Variable Used: wgLookup # # returns: valuematchset array selected # def findAddAttribWgLookup( rec, winery, value, fldWine, AbbrLookup=[], defaultorderlist=None, valueDescr='', debug=False ): # local variable - capture all the entries that are single match entries singlematch=[] # debugging if debug: try: print('faawl:value:', valueDescr, ':match-wgLookup:', rec[fldWine], ':', wgLookup[winery][value]) except Exception as e: print('debug error7-continuing:', str(e)) print('fldWine:', fldWine) # for each set of values that could be a match for valuematchset in wgLookup[winery][value]: # debugging if debug: print('faawl:testing valuematchset:', valuematchset, ':length:', len(valuematchset)) # set the flag to start allmatch = True # loop through the set of values that make up this set for valuematch in valuematchset: # for each entry - build a regex and test it and add it up # we need all values in this valueset to be true for this valueset to be match reMatch1 = re.compile(r'\b'+valuematch+r'\b', re.IGNORECASE) reMatch2 = re.compile(r'\s'+valuematch+r'\s', re.IGNORECASE) # check to see if this regex is a match m1 = reMatch1.search(rec[fldWine]) m2 = reMatch2.search(rec[fldWine]) if m1 or m2: # this regex is a match allmatch = True and allmatch elif valuematch in AbbrLookup: # this regex was not a match - but we want to check if the value also has # a translation - and if it has a translation - then we test the translation also # the value did not work but there is an alternate value to check # debugging if debug: print('faawl:valuematch-abbr:', valuematch, ':', wineAbbrLookup[valuematch]) # create the regex reMatch = re.compile(wineAbbrLookup[valuematch], re.IGNORECASE) # test the regex and attach the results to allmatch allmatch = reMatch.search(rec[fldWine]) and allmatch else: # not a match - update allmatch allmatch = False and allmatch # debugging if debug: print('faawl:valuematch:', valuematch, ':allmatch:', allmatch) # check to see if all matched if allmatch: # all matched - so this is a match - so break out of the valuematchset group # debugging if debug: print('faawl:value matched:', valuematchset) # different action based on # of items being match if len(valuematchset) == 1: # debugging if debug: print('faawl:single-valuematch-set-added-to-singlematch:', valuematchset) # single value matching - we don't stop when we find a match singlematch.append(valuematchset) else: # debugging if debug: print('faawl:multivalue-valuematch-set-found:done') # multi value match so we are done when we find a match - so return return valuematchset # did not find matchset in the for loop - check to see if we have singlematch if not singlematch: # debugging if debug: print('faawl:exit with singlematch NOT populated return blank') # did not have singlematch found - we are done - return empty return [] # singlematch populated # debugging if debug: print('faawl:exit with singlematch populated:', singlematch) # check to see how many matches we got if len(singlematch) == 1 or not defaultorderlist: # debugging if debug: print('faawl:return first entry in singlematch:', singlematch[0]) # if there is only one entry in here # or we don't have a default order so we pick the first found # and we set the value to this return singlematch[0] # we need to define which of the singlematch values we will return # the defaultorderlist will be used to set that ordering # # create a local copy of the list that can be changed in this routine defaultorder = defaultorderlist[:] # multiple singlematch values so lets find and pick the best one # debugging if debug: print('faawl:multiple single match value-singlematch:', singlematch) # get the values from singlematch that are not in defaultorder # and put them at the start of defaultorder list # go in reverse order when doing this lookup for val in singlematch[::-1]: if val not in defaultorder: defaultorder.insert(0,val) ### HARDCODED ### # very short term fix - we need to prioritze these single tags (mondavi problem) if winery == 'Mondavi' and ['Tok'] in singlematch: if debug: print('faawl:Change from:', valuematchset, ':to Tok for mondavi') return ['Tok'] # find the first matching value from priority order list for val in defaultorder: if val in singlematch: # debugging if debug: print('faawl:selected-singlematch-value:', val) # we found the first match - set it and break out return val # debugging if debug: print('faawl:valuematchset-empty') # did not match - return empty return [] ######################################################################################### # create a consistent wine name for a list or records with store based wine descriptions # # the special paramaters here are: # wgLookup - dictionary of winery, wine, list of wines # wines - list of records to be processed # # Global Variable Used: ignoreGrapeLookup, noGrapeLookup, wineAbbrLookup, liquorLookup # reCase, sizeLookup # # returns: [updated values in teh wines array] # #### Use the winery/grape-wine-liquour conversion table to define a wine description for the records def setWineryDescrFromWineryGrapeLookup( wgLookup, wines, fldWineDescr = 'winedescr', fldWine = 'wine', fldWineDescrNew = 'winedescrnew', fldWineDescrMatch=False, debug=False ): if debug: print('\n'*10,'START WINEDESCR SETTING HERE ---------------------------------------------') # step through all the records passed in for rec in wines: # local variables winery = grape = wine = vintage = case = size = liquor = nongrape = qual = None winematchset = grapematchset = [] # debugging if debug: try: print('setWinery:fldWine:', rec[fldWine]) except Exception as e: print('debug error2-continuing:', str(e)) print('fldWine:', fldWine) # make the field if it does not exist if fldWineDescrNew not in rec: rec[fldWineDescrNew] = rec[fldWineDescr] ### WINERY (winery, reWinery) = findWinery( rec, None, None, fldWine, debug=debug ) # validate the winery if winery is None: ### WINERY NONE - go to next record # debugging if debug: print('setWinery:winery not found-next record:' + rec[fldWine]) # get the next record continue elif winery not in wgLookup: ### WINERY NOT IN LOOKUP # skip this record - nothing to process # debugging if debug: print('setWinery:winery not in wgLookup:', winery) continue ### GRAPE # find the grape that is this record (grape, reGrape) = findGrapeByRegex( rec, fldWine, debug=debug ) # debugging if debug: print('setWinery:grape found:', grape) ### OVERRIDES if winery in ignoreGrapeLookup: ### IGNORE GRAPE # debugging if debug: print('setWinery:winery-match-ignoreGrape:clear-wine:set-grape-to-None:set-nongrape-True:winery:', winery) # clear wine and grape wine = '' # clear the grape field grape = None # set the liquor flag to control processing nongrape = True if winery in noGrapeLookup: ### NOGRAPE - WINE # debugging if debug: print('setWinery:noGrapeLookup wine check:', winery) # do the lookup and if a search is a match on None take appropriate action wine = wineLookupByName( noGrapeLookup[winery], rec[fldWine], [], 'noGrapeLookup', wineAbbrLookup, debug=debug ) # debugging if debug: print('setWinery:nogrape check:wine:', wine) # test the value we got back if wine == '': # debugging if debug: print('setWinery:noGrapeLookup:matched:None::clear grape:set nongrape to True') # the lookup match None - so we want to ignore any grape found and we blank out the wine grape = None wine = '' nongrape = True elif wine: # matched a wine - so clear the grape value grape = None # debugging if debug: print('setWinery:nograpeLookup:wine found - clear grape field') if wine is None and winery in liquorLookup: ### LIQUOR # debugging if debug: print('setWinery:liqourLookup:', winery) (liquor, reLiquor) = findLiquor( rec, winery, fldWine, debug=debug) # if we found something update wine to be what we found if liquor is not None: wine = liquor # debugging if debug: print('setWinery:liquorLookup-match:', liquor) if not grape and not nongrape and not wine and liquor is None: # NO GRAPE - and not connected to noGrapeLookup or liquorLookkup # get the next record # debugging if debug: print('setWinery:did not find grape-skipping record:', rec[fldWineDescr]) continue # debugging if debug: print('setWinery:pre-vintage found values for wine/liquor:', wine, ':grape:', grape) ### VINTAGE vintage = findVintage( rec, fldWine, debug=debug ) # debugging if debug: print('setWinery:vintage:', vintage) ### CASE information if reCase.search(rec[fldWine]): case = 'case' ### BOTTLE SIZE - get the size information for (size, reSize) in sizeLookup: # debugging if debug: print('setWinery:sizeLookup:',size) if reSize.search(rec[fldWine]) and not reShipsAs.search(rec[fldWine]): # debugging if debug: print('setWinery:sizeLookup:matched:',reSize) break else: size = None if debug: print('setWinery:sizeLookup:None-found') ### QUAL for this wine qual = findQualifier(rec[fldWine], debug=debug) # debugging if debug: try: print('setWinery:FinalAttributes:', winery, ':', grape, ':', wine, ':', liquor, ':', vintage, ':', case, ':', size, ':', qual, ':', rec[fldWine]) except Exception as e: print('debug error5-continuing:', str(e)) print('fldWine:', fldWine) ### WINE - ADDITIONAL INFORMATION if liquor is not None: # debugging if debug: print('setWinery:liquor flag set - no additional data needs to be collected') elif wine is not None: # debugging if debug: print('setWinery:wine is not None - do additional lookups:wine:', wine) # we found a wine / liquor - so see if there are additional attributes if wine in wgLookup[winery] and wgLookup[winery][wine]: # debugging if debug: print('setWinery:lookup winematchset') # there is one or more additional lookups for this winery/wine winematchset = findAddAttribWgLookup( rec, winery, wine, fldWine, wineAbbrLookup, None, valueDescr='wine', debug=debug ) else: # wine not in wgLookup so thing to work print('setWinery:unable to perform wgLookup on winery:', winery, ':wine:', wine, ':rec-wine:', rec[fldWine]) # debugging if debug: try: print('wgLookup[winery]:', wgLookup[winery]) except Exception as e: print('debug error3-continuing:', str(e)) print('winery:', winery) # debugging - wine is not None - what is the final winematchset if debug: print('setWinery:winematchset:', winematchset) elif grape is not None: # debugging if debug: print('setWinery:grape is not None - do additional lookups:', grape) # grape was returned (not wine) so do the lookup on grape if grape in wgLookup[winery] and wgLookup[winery][grape]: # see if we can create a match based on attributes and the grape grapematchset = findAddAttribWgLookup( rec, winery, grape, fldWine, wineAbbrLookup, defaultorderlist, valueDescr='grape', debug=debug ) elif grape in wgLookup[winery]: # do nothing this is a empty set if debug: print('setWinery:grape match: matching record set is blank - no action required') else: # wine not in wgLookup so thing to work # debugging print('setWinery:grape NONMATCH:', rec[fldWine]) if debug: print('setWinery:liquor:', liquor, ':wine:', wine, ':grape:', grape, ':wgLookup[winery]:', wgLookup[winery]) # debugging - wine is not None - what is the final grapematchset if debug: print('setWinery:grapematchset:', grapematchset) ### check the matchsets we got back - if any of them look like vintage values ### remove them from the string and look at up vintage again if vintage: newVintageLookupWine = rec[fldWine] for matchvalue in winematchset: if vintage in matchvalue: newVintageLookupWine = newVintageLookupWine.replace(matchvalue,'') if debug: print('setWinery:2nd-vintage:winematchset:wine-name-removal:', matchvalue) for matchvalue in grapematchset: if vintage in matchvalue: newVintageLookupWine = newVintageLookupWine.replace(matchvalue,'') if debug: print('setWinery:2nd-vintage:grapematchset:wine-name-removal:', matchvalue) if newVintageLookupWine != rec[fldWine]: if debug: print('setWinery:2nd-vintage:newVintageLookupWine:', newVintageLookupWine) newVintage = findVintage( { fldWine : newVintageLookupWine}, fldWine, debug=debug ) if debug: print('setWinery:2nd-vintage:newVintage:', newVintage) vintage = newVintage ### FINAL WINEDESCR # create initial value wineDescr = '' # if winery starts with a z then we don't have a vintage if winery.startswith('z'): vintage = None # debugging if debug: print('setWinery:winery starts with z: clear vintage') # quick test - does the wine and the winematchset the same if winematchset and ' '.join(winematchset) in wine: #debugging if debug: print('setWinery:clearing-winematchset:', winematchset,':is-in-wine:', wine) winematchset = [] if grapematchset and ' '.join(grapematchset) in grape: #TODO - work around for single letter matches if not (len(grapematchset)==1 and len(grapematchset[0])==1): #debugging if debug: print('setWinery:clearing-grapematchset:',grapematchset,':is-in-grape:', grape) grapematchset = [] if grapematchset and size and size in ' '.join(grapematchset): size = '' if winematchset and size and size in ' '.join(winematchset): size = '' if debug: print('setWinery:vallist1:', [winery, grape, wine] + grapematchset + winematchset + [vintage, size, qual, case]) print('setWinery:vallist2:', [winery, grape, wine, *grapematchset, *winematchset, vintage, size, qual, case]) # create a list wdList= [] # step through the values for val in [winery, grape, wine] + grapematchset + winematchset + [vintage, size, qual, case]: # and if there is a value add to the list - otherwise skip if val: wdList.append(val) # build the wine description by joining all these values together wineDescr = ' '.join(wdList) # debugging if False: if debug: print('setWinery:wdList:', wdList) if debug: print('setWinery:wineDescr:', wineDescr) # debugging if debug: try: print(':'.join(['setWinery:wineDescrList', wineDescr, rec[fldWineDescr], str(wineDescr==rec[fldWineDescr]), rec[fldWine]]) ) except Exception as e: print('debug error6-continuing:', str(e)) print('fldWine:', fldWine) # fill thew new value into the array rec[fldWineDescrNew] = wineDescr # fill in the matching field if fldWineDescrMatch: rec[fldWineDescrMatch] = (rec[fldWineDescr] == rec[fldWineDescrNew]) ######################################################################################### # set any digit only field to the word passed def setDigitFld2Value( wines, fld, value, debug=False ): for rec in wines: if rec[fld].isdigit(): rec[fld] = value ######################################################################################### # validate the field settings match the file we read in for update def updateFileOptionDictCheck( optiondict, wines, header, debug=False ): # check to see if the description field is in the file we read in if optiondict['fldWineDescr'] not in wines[0]: if debug: print('updateFileOptionDictCheck:fldWineDescr NOT in file read in:', optiondict['fldWineDescr']) # field needed is not in the record - see if we know what to do if 'cnt' in wines[0]: # the cnt field is in the file - so set to that structure # we will put the updated values into the 'cnt' field print('setting values fldWineDescr and fldWineDescrNew to: cnt') # change the field we are updating optiondict['fldWineDescr'] = optiondict['fldWineDescrNew'] = 'cnt' elif 'winedescr' in wines[0]: # the WineDescr field is in the file - so set to that structure print('setting values fldWineDescr to winedescr and fldWineDescrNew to winedescrnew') # change the field we are updating optiondict['fldWineDescr'] = 'winedescr' optiondict['fldWineDescrNew'] = 'winedescrnew' else: # no idea - we need to error out print('could not find fldWineDescr in wines[0]-aborting:', optiondict['fldWineDescr'], '\nwines[0]:', wines[0]) # force the error error = wines[0][optiondict['fldWineDescr']] # determine if we should create the match column (may want ot remove this section later) # removed this logic - require the person to set this field - we will not set it for them. if False and optiondict['fldWineDescr'] == 'winedescr': # we are using the file format that is the xref file # so check to see if we have match enabled if not optiondict['fldWineDescrMatch']: # create the default value optiondict['fldWineDescrMatch'] = 'same' # provide message print('setting value fldWineDescrMatch to: same') # check to see if the input file is the same as the output file if optiondict['csvfile_update_in'] == optiondict['csvfile_update_out']: # they are the same file (in and out) - so we need to move the input file to a backup location (file_path, base_filename, file_ext) = kvutil.filename_split(optiondict['csvfile_update_in']) # create the new filename backupfile = kvutil.filename_proper( base_filename + optiondict['backupfile_ext'], file_path ) # messaging print('copying ', optiondict['csvfile_update_in'], ' to ', backupfile) # copy the input file to the backup filename shutil.copyfile(optiondict['csvfile_update_in'], backupfile) # set the output keys we are going to assign if optiondict['fldWineDescrNew'] == 'cnt': # output matches the original ref file format with the "cnt" field optiondict['csvdictkeys'] = ['cnt','date','search','store','wine','winesrt'] elif optiondict['fldWineDescrMatch']: # output is a modified xref format so you can look at old and new definitions # optiondict['csvdictkeys'] = [optiondict['fldWineDescr'],optiondict['fldWineDescrNew'],optiondict['fldWineDescrMatch'], 'date','search','company','wine','winesrt'] optiondict['csvdictkeys'] = [optiondict['fldWineDescr'],optiondict['fldWineDescrNew'],optiondict['fldWineDescrMatch'], *header] else: # copy over the read in format optiondict['csvdictkeys'] = [optiondict['fldWineDescrNew']] + header[1:] # output matches expected input - should really change this to be the format of the read in file #optiondict['csvdictkeys'] = [optiondict['fldWineDescrNew'], 'date','search','company','wine','winesrt'] print('updateFileOptionDictCheck:set csvdictkeys to:',optiondict['csvdictkeys']) # --------------------------------------------------------------------------- if __name__ == '__main__': # capture the command line optiondict = kvutil.kv_parse_command_line( optiondictconfig, debug=False ) # set the global debug flag ppFlag = optiondict['pprint'] # set master fields setOptionDictMasterFldValues( optiondict, debug=False ) ### global variable checks ### if optiondict['setup_check']: print('Running global variable check') globalVariableCheck( debug = optiondict['debug'] ) sys.exit() # messaging print('reading in master file:', optiondict['csvfile_master_in']) # read in the MASTER FILE INPUT file wines,header = kvcsv.readcsv2list_with_header(optiondict['csvfile_master_in'], headerlc=True) # build the wine lookup dictionary wgLookup = buildWineryGrapeLookup( wines, optiondict['fldWineDescrMaster'], optiondict['fldWineMaster'], debug=optiondict['debug'] ) # read in the UPDATE FILE INPUT file - if not updating the master file if optiondict['csvfile_master_in'] != optiondict['csvfile_update_in']: # messaging print('reading in update file:', optiondict['csvfile_update_in']) # read in the INPUT file wines,header = kvcsv.readcsv2list_with_header(optiondict['csvfile_update_in'], headerlc=True) # check to see if we read in any records and if not just return if not wines: print('wineset.py - no records read in - no work to be done - exitting') sys.exit() # test to see if we should set the fields based on what we just read in updateFileOptionDictCheck( optiondict, wines, header, debug=optiondict['debug'] ) # do the assignment of wines to records setWineryDescrFromWineryGrapeLookup( wgLookup, wines, optiondict['fldWineDescr'], optiondict['fldWine'], optiondict['fldWineDescrNew'], optiondict['fldWineDescrMatch'], debug=optiondict['debug'] ) # if enabled - set all unassigned new descriptions the default value if optiondict['defaultnew'] is not None: # message print('Setting ', optiondict['fldWineDescrNew'], ' to ', optiondict['defaultnew'], 'if not set') # do the work setDigitFld2Value( wines, optiondict['fldWineDescrNew'], optiondict['defaultnew'], debug=optiondict['debug'] ) # save the output to the file of interest kvcsv.writelist2csv( optiondict['csvfile_update_out'], wines, optiondict['csvdictkeys'] ) # messaging print('Saved results to:', optiondict['csvfile_update_out'])
1
920cd41b18f5cfb45f46c44ed707cebe682d4dd9
Python
# Software License Agreement (BSD License) # # Copyright (c) 2009-2011, Eucalyptus Systems, Inc. # All rights reserved. # # Redistribution and use of this software in source and binary forms, with or # without modification, are permitted provided that the following conditions # are met: # # Redistributions of source code must retain the above # copyright notice, this list of conditions and the # following disclaimer. # # Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the # following disclaimer in the documentation and/or other # materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Author: [email protected] ''' @author: clarkmatthew extension of the boto instance class, with added convenience methods + objects Add common instance test routines to this class Examples: from eucaops import Eucaops from nephoria.windows_instance import WinInstance tester = Eucaops(credpath='eucarc-10.111.5.80-eucalyptus-sys_admin') wins = WinInstance.make_euinstance_from_instance(tester.get_instances(idstring='i-89E13DA8')[0], tester=tester, keypair='test') vol = tester.get_volume(status='available', zone=wins.placement) wins.attach_volume(vol) ''' import socket import os import re import time import copy import types import operator from prettytable import PrettyTable, ALL from boto.ec2.instance import Instance from nephoria.aws.ec2.euvolume import EuVolume from cloud_utils.log_utils import eulogger, get_line, markup from nephoria.euca.taggedresource import TaggedResource from boto.ec2.instance import InstanceState from datetime import datetime from cloud_utils.net_utils import winrm_connection termline = get_line() class WinInstanceDiskType(): gigabyte = 1073741824 megabyte = 1048576 def __init__(self, win_instance, wmic_dict): self.check_dict_requires(wmic_dict) self.__dict__ = self.convert_numbers_in_dict(copy.copy(wmic_dict)) self.win_instance = win_instance self.size_in_gb = self.get_size_in_gb() self.size_in_mb = self.get_size_in_mb() self.size = long(self.size or 0) self.last_updated = time.time() self.setup() def setup(self): raise Exception('Not Implemented') def check_dict_requires(self, wmic_dict): raise Exception('Not Implemented') def convert_numbers_in_dict(self, dict): #convert strings representing numbers to ints for key in dict: value = str(dict[key]) if (re.search("\S", str(dict[key])) and not re.search("\D", str(dict[key]))): dict[key] = long(dict[key]) return dict def get_partition_ids(self): retlist = [] for part in self.disk_partitions: retlist.append(part.deviceid) return retlist def get_logicaldisk_ids(self): retlist = [] for part in self.disk_partitions: retlist.extend(part.get_logicaldisk_ids()) return retlist def get_size_in_gb(self): ''' Attempts to convert self.size from bytes to gigabytes as well as round up > .99 to account for a differences in how the size is represented ''' self.size = int(self.size or 0) gigs = self.size / self.gigabyte if (self.size % self.gigabyte) /float(self.gigabyte) > .99: gigs += 1 return gigs def get_size_in_mb(self): ''' Attempts to convert self.size from bytes to gigabytes as well as round up > .99 to account for a differences in how the size is represented ''' self.size = int(self.size or 0) mb = self.size / self.megabyte if (self.size % self.megabyte) /float(self.megabyte) > .99: mb += 1 return mb def print_self(self): self.get_summary(printmethod=self.win_instance.debug) def get_summary(self, printheader=True, printmethod=None): raise Exception('Method not implemented') def print_self_full(self, printmethod=None): ''' formats and prints self.dict ''' self.win_instance.print_dict(dict=self.__dict__, printmethod=printmethod) class WinInstanceDiskDrive(WinInstanceDiskType): def setup(self): if not hasattr(self, 'serialnumber'): self.serialnumber = '' if not hasattr(self, 'caption'): self.caption = '' if hasattr(self, 'model'): self.caption = self.model else: self.model = self.caption self.cygwin_scsi_drive = self.win_instance.get_cygwin_scsi_dev_for_windows_drive(windisk=self) self.update_ebs_info() self.disk_partitions = [] def check_dict_requires(self, wmic_dict): if not ('deviceid' in wmic_dict and 'size' in wmic_dict and ('caption' in wmic_dict or 'model in wmic_dict') and 'index' in wmic_dict): raise Exception('wmic_dict passed does not contain needed attributes; deviceid, size, caption, and index') def get_partition_ids(self): retlist = [] for part in self.disk_partitions: retlist.append(part.deviceid) return retlist def get_logicaldisk_ids(self): retlist = [] for part in self.disk_partitions: retlist.extend(part.get_logicaldisk_ids()) return retlist def update_md5_info_from_ebs(self): self.md5 = None self.md5len = None for vol in self.win_instance.attached_vols: if vol.guestdev == self.deviceid: if not vol.md5: vol.md5len = 1024 vol.md5 = self.win_instance.get_dev_md5(self.cygwin_scsi_drive, vol.md5len) self.md5 = vol.md5 self.md5len = vol.md5len break def update_ebs_info_from_serial_number(self): ''' Attempts to parse the serial number field from an EBS volume and find the correlating ebs volume example format: vol-81C13EA4-dev-sdg ''' if re.match("^vol-", self.serialnumber): split = self.serialnumber.split('-') self.ebs_volume = str(split[0]) + "-" + str(split[1]) self.ebs_cloud_dev = "/" + str(split[2]) + "/" + str(split[3]) else: self.ebs_volume = '' self.ebs_cloud_dev = '' def update_ebs_info(self): self.update_ebs_info_from_serial_number() if not self.ebs_volume: if self.index == 0 and self.win_instance.root_device_type == 'ebs': bdm = self.win_instance.block_device_mapping[self.win_instance.root_device_name] self.ebs_volume = bdm.volume_id else: for vol in self.win_instance.attached_vols: if vol.guestdev == self.deviceid: self.ebs_volume = vol.id break if not self.ebs_cloud_dev and self.ebs_volume: volume = self.win_instance.tester.get_volume(volume_id=self.ebs_volume) if hasattr(volume,'attach_data') and volume.attach_data: self.ebs_cloud_dev = volume.attach_data.device self.update_md5_info_from_ebs() def get_summary(self, printheader=True, printmethod=None): buf = "" deviceid = 20 size = 16 sizegb = 7 ebsvol = 12 serialnumber = 24 caption = 36 part_count = 6 logical_ids = 8 cygdrive = 10 md5 = 32 header = "DISKDRIVE DEV ID".center(deviceid) + "|" + \ "SIZE B".center(size) + "|" + \ "SIZE GB".center(sizegb) + "|" + \ "EBS VOL".center(ebsvol) + "|" + \ "CAPTION".center(caption) + "|" + \ "PARTS".center(part_count) + "|" + \ "LOGICAL".center(logical_ids) + "|" + \ "CYGDRIVE".center(cygdrive) + "|" + \ "SERIAL NUMBER".center(serialnumber) + "|" + \ "MD5 CHECK SUM".center(md5) + "|" summary = str(self.deviceid).center(deviceid) + "|" + \ str(self.size).center(size) + "|" + \ str(self.size_in_gb).center(sizegb) + "|" + \ str(self.ebs_volume).center(ebsvol) + "|" + \ str(self.caption).center(caption) + "|" + \ str(self.partitions).center(part_count) + "|" + \ str(",".join(str(x) for x in self.get_logicaldisk_ids())).center(logical_ids) + "|" + \ str(self.cygwin_scsi_drive).center(cygdrive) + "|" + \ str(self.serialnumber).center(serialnumber) + "|" + \ str(self.md5).center(md5) + "|" length = len(header) if len(summary) > length: length = len(summary) line = get_line(length) if printheader: buf += line + header + line buf += summary + line if printmethod: printmethod(buf) return buf class WinInstanceDiskPartition(WinInstanceDiskType): def setup(self): #self.cygwin_scsi_drive = self.win_instance.get_cygwin_scsi_dev_for_windows_drive(drive_id=self.deviceid) self.logicaldisks = [] #Set values in case 'brief' was used when fetching partitions if not hasattr(self,'deviceid'): self.deviceid = self.name if not hasattr(self,'bootable'): self.bootable = self.bootpartition if not hasattr(self,'diskindex'): self.diskindex = self.get_disk_index_from_name() def check_dict_requires(self, wmic_dict): if not ('name' in wmic_dict and 'size' in wmic_dict and 'bootpartition' in wmic_dict and 'index' in wmic_dict): raise Exception('wmic_dict passed does not contain needed attributes; deviceid, size, index and bootable') def get_disk_index_from_name(self): diskindex = None diskindexstring = self.name.split(',')[0] if re.search('disk', diskindexstring, re.IGNORECASE): diskindex = int(diskindexstring.split('#')[1]) return diskindex def get_logicaldisk_ids(self): retlist = [] for disk in self.logicaldisks: retlist.append(disk.deviceid) return retlist def get_summary(self, printheader=True, printmethod=None): buf = "" deviceid = 24 size = 16 sizegb = 12 sizemb = 12 bootable = 10 header = "PARTITION DEV ID".center(deviceid) + "|" + \ "SIZE B".center(size) + "|" + \ "SIZE GB".center(sizegb) + "|" + \ "SIZE MB".center(sizemb) + "|" + \ "BOOTABLE".center(bootable) + "|" summary = str(self.deviceid).center(deviceid) + "|" + \ str(self.size).center(size) + "|" + \ str(self.size_in_gb).center(sizegb) + "|" + \ str(self.size_in_mb).center(sizemb) + "|" + \ str(self.bootable).center(bootable) + "|" length = len(header) if len(summary) > length: length = len(summary) line = get_line(length) if printheader: buf += line + header + line buf += summary + line if printmethod: printmethod(buf) return buf class WinInstanceLogicalDisk(WinInstanceDiskType): def setup(self): self.cygwin_scsi_drive = self.win_instance.get_cygwin_scsi_dev_for_windows_drive(windisk=self) self.partition = None def check_dict_requires(self, wmic_dict): if not ('deviceid' in wmic_dict and 'size' in wmic_dict and 'description' in wmic_dict and 'freespace' in wmic_dict and 'filesystem' in wmic_dict): raise Exception('wmic_dict passed does not contain needed attributes; deviceid, size, and description') def get_summary(self, printheader=True, printmethod=None): buf = "" deviceid = 24 size = 16 freespace = 16 filesystem = 24 description = 30 cygdrive = 10 header = "LOGICAL DEV ID".center(deviceid) + "|" + \ "SIZE".center(size) + "|" + \ "FREE SPACE".center(freespace) + "|" + \ "FILE SYSTEM".center(filesystem) + "|" + \ "DESCRIPTION".center(description) + "|" + \ "CYGDRIVE".center(cygdrive) + "|" summary = str(self.deviceid).center(deviceid) + "|" + \ str(self.size).center(size) + "|" + \ str(self.freespace).center(freespace) + "|" + \ str(self.filesystem).center(filesystem) + "|" + \ str(self.description).center(description) + "|" + \ str(self.cygwin_scsi_drive).center(cygdrive) + "|" length = len(header) if len(summary) > length: length = len(summary) line = get_line(length) if printheader: buf += line + header + line buf += summary + line if printmethod: printmethod(buf) return buf class WinInstance(Instance, TaggedResource): gigabyte = 1073741824 megabyte = 1048576 @classmethod def make_euinstance_from_instance(cls, instance, tester, debugmethod = None, keypair=None, keypath=None, password=None, username="Administrator", auto_connect = True, verbose=True, timeout=120, private_addressing = False, reservation = None, cmdstart=None, try_non_root_exec=True, winrm_port='5985', winrm_protocol='http', rdp_port='3389', rootfs_device = "sda", block_device_prefix = "sd", bdm_root_vol = None, virtio_blk = True, cygwin_path = None, disk_update_interval=10, retry=2, brief=False ): ''' Primary constructor for this class. Note: to avoid an ssh session within this method, provide keys, username/pass later. Arguments: instance - mandatory- a Boto instance object used to build this euinstance object keypair - optional- a boto keypair object used for creating ssh connection to the instance username - optional- string used to create ssh connection as an alternative to keypair password - optional- string used to create ssh connection to this instance as an alternative to keypair exec_password -optional -string used for su or sudo where prompted for password, will default to 'password' auto_connect -optional -boolean, if True will attempt to automatically create an ssh session for this instance try_non_root_exec -optional -boolean, if True will attempt to use sudo if available else su -c to execute privileged commands timeout - optional- integer used for ssh connection timeout debugmethod - optional - method, used for debug output verbose - optional - boolean to determine if debug is to be printed using debug() retry - optional - integer, ssh connection attempts for non-authentication failures ''' newins = WinInstance(instance.connection) newins.__dict__ = instance.__dict__ newins.tester = tester newins.winrm_port = winrm_port newins.rdp_port = rdp_port newins.bdm_root_vol = None newins.winrm_protocol = winrm_protocol newins.debugmethod = debugmethod if newins.debugmethod is None: newins.log = eulogger.Eulogger(identifier= str(instance.id)) newins.debugmethod= newins.log.debug if (keypair is not None): if isinstance(keypair,types.StringTypes): keyname = keypair keypair = tester.get_keypair(keyname) else: keyname = keypair.name newins.keypath = keypath or os.getcwd() + "/" + keyname + ".pem" newins.keypair = keypair newins.password = password newins.username = username newins.verbose = verbose newins.attached_vols=[] newins.timeout = timeout newins.virtio_blk = virtio_blk newins.disk_update_interval = disk_update_interval newins.retry = retry newins.brief = brief newins.rootfs_device = rootfs_device newins.block_device_prefix = block_device_prefix newins.private_addressing = private_addressing newins.reservation = reservation or newins.get_reservation() if newins.reservation: newins.security_groups = newins.tester.get_instance_security_groups(newins) else: newins.security_groups = None newins.laststate = newins.state newins.cmdstart = cmdstart newins.auto_connect = auto_connect newins.set_last_status() newins.update_vm_type_info() newins.cygwin_path = cygwin_path newins.system_info = None newins.diskdrives = [] newins.disk_partitions = [] newins.logicaldisks = [] newins.cygwin_dev_map = {} #newins.set_block_device_prefix() if newins.root_device_type == 'ebs': try: volume = newins.tester.get_volume(volume_id = newins.block_device_mapping.get(newins.root_device_name).volume_id) newins.bdm_root_vol = EuVolume.make_euvol_from_vol(volume, tester=newins.tester,cmdstart=newins.cmdstart) except:pass newins.winrm = None if newins.auto_connect and newins.state == 'running': newins.connect_to_instance(timeout=timeout) return newins @property def age(self): launchtime = self.tester.get_datetime_from_resource_string(self.launch_time) # return the elapsed time in seconds return (time.mktime(datetime.utcnow().utctimetuple()) - time.mktime(launchtime.utctimetuple())) def update(self, validate=False, dry_run=False, err_state='terminated', err_code=-1): ret = None tb = "" retries = 2 for x in xrange(0, retries): try: #send with validation True, fail later... ret = super(WinInstance, self).update(validate=True, dry_run=dry_run) break except ValueError: if validate: raise tb = self.tester.get_traceback() self.debug('Failed to update instance. Attempt:{0}/{1}' .format(x, retries)) if not ret: failmsg = 'Failed to update instance. Instance may no longer ' \ 'be present on system"{0}"'.format(self.id) self.debug('{0}\n{1}'.format(tb, failmsg)) self.debug('{0} setting fake state to:"{1}"'.format(self.id, err_state)) state = InstanceState(name=err_state, code=err_code) self._state = state ret = self.state self.set_last_status() return ret def update_vm_type_info(self): self.vmtype_info = self.tester.get_vm_type_from_zone(self.placement,self.instance_type) return self.vmtype_info def set_last_status(self,status=None): self.laststate = self.state self.laststatetime = time.time() self.age_at_state = self.tester.get_instance_time_launched(self) #Also record age from user's perspective, ie when they issued the run instance request (if this is available) if self.cmdstart: self.age_from_run_cmd = "{0:.2f}".format(time.time() - self.cmdstart) else: self.age_from_run_cmd = None def print_dict(self, dict=None, printmethod=None): ''' formats and prints ''' printmethod = printmethod or self.debug buf = "\n" dict = dict or self.__dict__ longest_key = 0 for key in dict: if len(key) > longest_key: longest_key = len(key) for key in dict: buf += str(key).ljust(longest_key) + " -----> :" + str(dict[key]) + "\n" printmethod(buf) def printself(self, title=True, footer=True, printmethod=None, printme=True): def state_markup(state): # Markup instance state... if state == 'running': return markup(state, markups=[1, 92]) if state == 'terminated': return markup(state, markups=[1, 97]) if state == 'shutting-down': return markup(state, markups=[1, 95]) if state == 'pending': return markup(state, markups=[1, 93]) if state == 'stopped': return markup(state, markups=[1, 91]) else: return markup(state, markups=[1, 91]) def multi_line(lines): # Utility method for creating multi line table entries... buf = "" maxlen = 0 for line in lines: if len(line) + 2 > maxlen: maxlen = len(line) + 2 for line in lines: buf += str(line).ljust(maxlen) + "\n" buf = buf.rstrip() return (buf, maxlen) bdmvol = self.root_device_type if self.bdm_root_vol: bdmvol += ":" + self.bdm_root_vol.id reservation_id = None if self.reservation: reservation_id = self.reservation.id owner_id = self.reservation.owner_id else: owner_id = "???" # Create a multi line field for instance's run info idlist = [markup("{0} {1}".format('ID:', self.id), markups=[1, 4, 94]), "{0} {1}".format(markup('TYPE:'), self.instance_type), "{0} {1}".format(markup('RES:'), reservation_id), "{0}".format(markup("ACCOUNT ID:")), owner_id] id_string, idlen = multi_line(idlist) try: emi = self.tester.get_emi(self.image_id) emi_name = str(emi.name[0:18]) + ".." except: emi_name = "" # Create a multi line field for the instance's image info virt_type = 'PV' if self.virtualization_type == 'hvm': virt_type = 'HVM' emi_string, emilen = multi_line( [markup("{0} {1}".format('EMI:', self.image_id)), "{0} {1}".format(markup('OS:'), self.platform or 'linux'), "{0} {1}".format(markup('VIRT:'), virt_type), "{0}".format(markup('IMAGE NAME:')), emi_name]) # Create a multi line field for the instance's state info if self.age: age = int(self.age) state_string, state_len = multi_line(["STATE: " + state_markup(self.laststate), "{0} {1}".format(markup('AGE:'), age), "{0} {1}".format(markup("ZONE:"), self.placement), markup('ROOTDEV:'), bdmvol]) # Create the primary table called pt... netinfo = 'INSTANCE NETWORK INFO:' idheader = 'INSTANCE ID' imageheader = 'INSTANCE IMAGE' stateheader = 'INSTANCE STATE' pt = PrettyTable([idheader, imageheader, stateheader, netinfo]) pt.align[netinfo] = 'l' pt.valign[netinfo] = 'm' pt.align[idheader] = 'l' pt.align[imageheader] = 'l' pt.align[stateheader] = 'l' pt.max_width[idheader] = idlen pt.max_width[imageheader] = emilen pt.max_width[stateheader] = state_len pt.padding_width = 0 pt.hrules = ALL # PrettyTable headers do not work with ascii markups, so make a sudo header new_header = [] for field in pt._field_names: new_header.append(markup(field, markups=[1, 4])) pt.add_row(new_header) pt.header = False # Create a subtable 'netpt' to summarize and format the networking portion... # Set the maxwidth of each column so the tables line up when showing multiple instances vpc_col = ('VPC', 4) subnet_col = ('SUBNET', 6) if self.vpc_id: vpc_col = ('VPC', 12) subnet_col = ('SUBNET', 15) secgrp_col = ('SEC GRPS', 11) privaddr_col = ('P', 1) privip_col = ('PRIV IP', 15) pubip_col = ('PUB IP', 15) net_cols = [vpc_col, subnet_col, secgrp_col, privaddr_col, privip_col, pubip_col] # Get the Max width of the main tables network summary column... # Start with 2 to account for beginning and end column borders netinfo_width = 2 netinfo_header = [] for col in net_cols: netinfo_width += col[1] + 1 netinfo_header.append(col[0]) pt.max_width[netinfo] = netinfo_width netpt = PrettyTable([vpc_col[0], subnet_col[0], secgrp_col[0], privaddr_col[0], privip_col[0], pubip_col[0]]) netpt.padding_width = 0 netpt.vrules = ALL for col in net_cols: netpt.max_width[col[0]] = col[1] sec_grps = [] for grp in self.groups: sec_grps.append(str(grp.id)) sec_grps = ",".join(sec_grps) private_addressing = "N" if self.private_addressing: private_addressing = "Y" netpt.add_row([str(self.vpc_id).center(vpc_col[1]), str(self.subnet_id).center(subnet_col[1]), str(sec_grps).center(secgrp_col[1]), str(private_addressing).center(privaddr_col[1]), str(self.private_ip_address).center(privip_col[1]), str(self.ip_address).center(pubip_col[1])]) # To squeeze a potentially long keyname under the network summary table, get the length # and format this column to allow for wrapping a keyname under the table... # netbuf = netpt.get_string() netbuf = "{0}:{1} {2}:{3}\n".format(markup("NODE"), self.tags.get('euca:node', "???").ljust(16), markup("KEYPAIR"), self.key_name) netbuf += "\n".join(netpt.get_string().splitlines()[0:-1]) # Create the row in the main table... pt.add_row([id_string, emi_string, state_string, netbuf]) if printme: printmethod = printmethod or self.log.debug printmethod("\n" + str(pt) + "\n") return pt def get_password(self, private_key_path=None, key=None, dir=None, exten=".pem", encoded=True, force_update=False): ''' :param private_key_path: private key file used to decrypt password :param key: name of private key :param dir: Path to private key :param exten: extension of private key :param encoded: boolean of whether string returned from server is Base64 encoded :return: decrypted password ''' if self.password is None or force_update: self.password = self.tester.get_windows_instance_password( self, private_key_path=private_key_path, key=key, dir=dir, exten=exten, encoded=encoded) return self.password def reset_ssh_connection(self, timeout=None): # todo: Remove ssh reference from this method, use something like # reset_instance_connection, etc.. self.debug('Note ssh not implemented at this time, using winrm for ' 'shell access instead...') return self.reset_winrm_connection(timeout=timeout) def reset_winrm_connection(self, timeout=None, force=False): # todo: timeout = timeout or self.timeout self.debug('reset_winrm_connection for:'+str(self.id)) self.get_password(force_update=True) if self.username is None or self.password is None: #Allow but warn here as this may be a valid negative test self.debug('Warning username and/or password were None in ' 'winrm connnection?') # Create a new winrm interface if this is a new instance or # an attribute has changed... try: #Check the port in order to provide debug if the connection fails self.test_port_status(port=self.winrm_port, ip=self.ip_address) except:pass if force or not (self.winrm and \ self.winrm.hostname == self.ip_address and \ self.winrm.username == self.username and \ self.winrm.password == self.password): if self.winrm: self.winrm.close_shell() self.winrm = winrm_connection.Winrm_Connection( hostname = self.ip_address, username = self.username, password = self.password, port = self.winrm_port, protocol = self.winrm_protocol, debug_method = self.debug, verbose=True ) def get_reservation(self): res = None try: res = self.tester.get_reservation_for_instance(self) except Exception, e: self.update() self.debug('Could not get reservation for instance in state:' + str(self.state) + ", err:" + str(e)) return res def connect_to_instance(self, wait_for_boot=180, timeout=120): ''' Attempts to connect to an instance via ssh. :params wait_for_boot: time to wait, allowing guest to boot before attempting to poll for ports active status :params timeout: -optional - time in seconds to wait when polling port(s) status(s) before failure ''' self.debug("{0}connect_to_instance starting.\nwait_for_boot:{1} " "seconds\ntimeout from boot:{2}{3}" .format(termline, wait_for_boot, timeout, termline)) try: self.poll_for_port_status_with_boot_delay(waitforboot=wait_for_boot, timeout=timeout) except Exception, e: self.debug('Warning failed to poll port status:' + str(e)) self.debug("Attempting to create connection to instance:" + self.id) attempts = 0 start = time.time() elapsed = 0 if self.winrm is not None: self.winrm.close_shell() self.winrm = None while (elapsed < timeout): attempts += 1 try: self.update() self.reset_winrm_connection() self.debug('Try some sys...') self.sys("whoami") except Exception, se: tb = self.tester.get_traceback() self.debug('Caught exception attempting to connect ' 'winrm shell:\n'+ str(tb) + str(se)) elapsed = int(time.time()-start) self.debug('connect_to_instance: Attempts:' + str(attempts) + ', elapsed:'+str(elapsed)+'/'+str(timeout)) if self.winrm is not None: self.winrm.close_shell() self.winrm = None time.sleep(5) pass else: break elapsed = int(time.time()-start) if self.winrm is None: self.get_connection_debug() raise RuntimeError(str(self.id) + ":Failed establishing management connection to " "instance, elapsed:" + str(elapsed) + "/" + str(timeout)) self.debug('Connect_to_instance updating attached volumes/disk ' 'info for vols: ' + str(self.attached_vols)) if self.brief: self.update_system_info() else: self.update_system_and_disk_info() self.init_attached_volumes() self.debug("{0}connect_to_instance completed{1}" .format(termline, termline)) def get_connection_debug(self): # Add network debug/diag info here... # First show arp cache from local machine # todo Consider getting info from relevant euca components: # - iptables info # - route info # - instance xml try: # Show local ARP info... arp_out = "\nLocal ARP cache for instance ip: " \ + str(self.ip_address) + "\n" arp_fd = os.popen('arp ' + str(self.ip_address)) for line in arp_fd: arp_out += line self.debug(arp_out) except Exception as AE: self.log.debug('Failed to get arp info:' + str(AE)) try: self.tester.get_console_output(self) except Exception as CE: self.log.debug('Failed to get console output:' + str(CE)) def update_root_device_diskdrive(self): if not self.root_device_type == 'ebs': return for disk in self.diskdrives: if disk.index == 0: if disk.ebs_volume: for vol in self.attached_vols: if vol.id == disk.ebs_volume: if not disk.md5: disk.update_md5_info_from_ebs() return volume = self.tester.get_volume(volume_id=disk.ebs_volume) if not isinstance(volume, EuVolume): volume = EuVolume.make_euvol_from_vol(volume, self.tester) volume.guestdev = disk.deviceid volume.md5len = 1024 volume.md5 = self.get_dev_md5(disk.cygwin_scsi_drive, volume.md5len) if not self.get_volume_from_attached_list_by_id(volume.id): self.debug("{0} updating with root vol:{1}{2}" .format(termline, volume.id, termline)) self.attached_vols.append(volume) disk.update_md5_info_from_ebs() return def get_volume_from_attached_list_by_id(self, volume_id): for vol in self.attached_vols: if vol.id == volume_id: return vol def update_system_and_disk_info(self): try: self.update_system_info() except Exception, sie: tb = self.tester.get_traceback() self.debug(str(tb) + "\nError updating system info:" + str(sie)) try: self.update_disk_info() self.update_root_device_diskdrive() self.print_partition_summary() self.print_logicaldisk_summary() self.print_diskdrive_summary() except Exception, ude: tb = self.tester.get_traceback() self.debug(str(tb) + "\nError updating disk info:" + str(ude)) def has_sudo(self): return False def debug(self,msg,traceback=1,method=None,frame=False): ''' Used to print debug, defaults to print() but over ridden by self.debugmethod if not None msg - mandatory -string, message to be printed ''' if ( self.verbose is True ): self.debugmethod(msg) def sys(self, cmd, verbose=True, code=None, include_stderr=False, enable_debug=False, timeout=None): ''' Issues a command against the ssh connection to this instance Returns a list of the lines from stdout+stderr as a result of the command cmd - mandatory - string, the command to be executed verbose - optional - boolean flag to enable debug timeout - optional - command timeout in seconds ''' if (self.winrm is None): raise Exception("WinInstance winrm connection is None") return self.winrm.sys(command=cmd, include_stderr=include_stderr, timeout=timeout, verbose=verbose, code=code) def test_rdp_port_status(self, ip=None, port=3389, timeout=10): ''' Description: Attempts to test that the host is accepting tcp connections to the RDP port ''' ip = ip or self.ip_address return self.test_port_status(ip=ip, port=port, timeout=timeout) def test_port_status(self, port, ip=None, timeout=5, tcp=True, verbose=True): ip = ip or self.ip_address return self.tester.test_port_status(ip, int(port), timeout=timeout, tcp=tcp, verbose=verbose) def poll_for_port_status_with_boot_delay(self, interval=15, ports=[], socktimeout=5,timeout=180, waitforboot=300): ''' Make sure some time has passed before we test on the guest side before running guest test... ''' launch_seconds = self.tester.get_instance_time_launched(self) sleeptime = 0 if launch_seconds > waitforboot else (waitforboot - launch_seconds) self.debug("Instance was launched "+str(launch_seconds)+" seconds ago, waiting:"+str(sleeptime)+" for instance to boot") time.sleep(sleeptime) return self.poll_for_ports_status(ports, ip=self.ip_address, interval=interval, socktimeout=socktimeout, timeout=timeout) def wait_for_time_since_launch(self,waitforboot=420): ''' When using larger instance store images, this can allow for the delays caused by image size/transfer. ''' boot_seconds = self.tester.get_instance_time_launched(self) sleeptime = 0 if boot_seconds > waitforboot else (waitforboot - boot_seconds) self.debug("Instance was launched "+str(boot_seconds)+"/"+str(waitforboot) + " seconds ago, waiting:"+str(sleeptime)+" for instance to boot") start = time.time() elapsed = 0 print "Waiting for Windows to fully boot:", while elapsed < sleeptime: print "Waiting for Windows to fully boot:"+str(sleeptime-elapsed), time.sleep(5) elapsed=int(time.time()-start) self.debug("test_wait_for_instance_boot: done waiting, instance up for "+str(waitforboot)+" seconds") def poll_for_ports_status(self, ports=[], ip=None, interval=10, socktimeout=5, timeout=180): ip = ip or self.ip_address ports = ports or [self.rdp_port, self.winrm_port] start = time.time() elapsed = 0 attempt = 0 while elapsed < timeout: attempt +=1 self.debug('test_poll_for_ports_status, ports: ' + ",".join(str(x) for x in ports) + ", attempt:" + str(attempt)) for port in ports: if elapsed < timeout: try: self.debug('Trying ip:port:' + str(self.ip_address) + ':' + str(port) + ", elapsed:" + str(elapsed)) self.test_port_status(ip=ip, port=int(port), timeout=5) return except socket.error, se: self.debug('test_ports_status failed socket error:'+str(se[0])) #handle specific errors here, for now just for debug... ecode=se[0] if ecode == socket.errno.ETIMEDOUT or ecode == "timed out": self.debug("test_poll_for_ports_status: Connect "+str(ip)+":" +str(port)+ " timed out retrying. Time remaining("+str(timeout-elapsed)+")") except Exception, e: tb = self.tester.get_traceback() self.debug(tb) self.debug('test_poll_for_ports_status:'+str(ip)+':'+str(port)+' FAILED after attempts:'+str(attempt)+', elapsed:'+str(elapsed)+', err:'+str(e) ) elapsed = int(time.time() -start) if elapsed < timeout: time.sleep(interval) raise Exception('test_poll_for_ports_status:'+str(ip)+':'+str(port)+' FAILED after attempts:'+str(attempt)+', elapsed:'+str(elapsed)+' seconds') def init_attached_volumes(self): self.debug('init_attahced_volumes... attached_vols: ' + str(self.attached_vols)) syncdict = self.sync_attached_volumes_with_clouds_view() if syncdict['errors']: errmsg = 'Errors syncing guest volumes with cloud at init:' + ",".join(str(e) for e in syncdict['errors']) errmsg += 'Failed to sync guest volumes with cloud at init:' + ",".join(str(x) for x in syncdict['badvols']) self.debug(errmsg) time.sleep(60) raise Exception(errmsg) def sync_attached_volumes_with_clouds_view(self): self.debug(termline + "Starting sync_attached_volumes_with_clouds_view" + termline ) badvols = [] errors = [] ret = {'errors':errors, 'badvols':badvols} #Get a list of volumes that the cloud believes are currently attached cloud_volumes = self.tester.get_volumes(attached_instance=self.id) #Make a copy of a list of volumes this instance thinks are currenlty attached locallist = copy.copy(self.attached_vols) self.debug('Cloud list:' + str(cloud_volumes)) self.debug('Local list:' + str(locallist)) for vol in cloud_volumes: for local_vol in locallist: if local_vol.id == vol.id: locallist.remove(local_vol) if not isinstance(vol, EuVolume): vol = EuVolume.make_euvol_from_vol(vol, self.tester) try: self.update_volume_guest_info(volume=vol) except Exception, e: badvols.append(vol) errors.append(vol.id + ' Error syncing with cloud:' + str (e) + '. \n') for local_vol in locallist: badvols.append(local_vol) errors.append(local_vol.id + ' Error unattached volume found in guests attach list. \n') self.debug(termline + "Finishing sync_attached_volumes_with_clouds_view" + termline ) return ret def update_system_info(self): ''' Gather basic system info for this windows instance object and store in self.system_info Example: # print wins.system_info.OS_NAME 'Microsoft Windows 7 Professional' ''' currentkey = None swap = re.compile('([!@#$%^&*. ])') info = self.sys('systeminfo') if self.system_info: system_info = self.system_info else: system_info = type('obj', (object,),{}) if info: for line in info: if re.match("^\w.+:", line): linevals = line.split(':') currentkey = linevals.pop(0) #clean up the key string... currentkey = re.sub('[()]', '', currentkey) currentkey = re.sub(swap, '_', currentkey) currentkey = currentkey.lower() value = ":".join(str(x) for x in linevals) or "" setattr(system_info, currentkey, str(value).strip()) elif currentkey: #this is an additional value to our previous key prev_value = getattr(system_info, currentkey) if not isinstance(prev_value, types.ListType): updated_value = [prev_value] updated_value.append(str(line).strip()) setattr(system_info, currentkey, updated_value) self.system_info = system_info def get_cygwin_path(self, prefix="c:\\"): if self.cygwin_path: return self.cygwin_path path = None self.debug('Trying to find cygwin path...') out = self.sys('dir ' + str(prefix) + ' /B') for line in out: if re.search('cygwin', line): path = str(prefix) + str(line.strip()) + "\\" self.cygwin_path = path break return path def cygwin_curl(self, url, connect_timeout=30): cygpath = self.get_cygwin_path() if cygpath is None: raise Exception('Could not find cygwin path on guest for curl?') curl = cygpath + 'bin\curl.exe --connect-timeout ' + str(connect_timeout) + ' ' return self.sys(curl + str(url), code=0, timeout=connect_timeout) def get_metadata(self, element_path='', prefix='latest/meta-data/', use_cygwin=True): """Return the lines of metadata from the element path provided""" ### If i can reach the metadata service ip use it to get metadata otherwise try the clc directly try: if use_cygwin: return self.cygwin_curl("http://169.254.169.254/"+str(prefix)+str(element_path), connect_timeout=10) else: return self.sys("curl --connect-timeout 10 http://169.254.169.254/"+str(prefix)+str(element_path), code=0) except: if use_cygwin: return self.cygwin_curl("http://" + self.tester.get_ec2_ip() + ":8773/"+str(prefix) + str(element_path)) else: return self.sys("curl http://" + self.tester.get_ec2_ip() + ":8773/"+str(prefix) + str(element_path), code=0) def print_diskdrive_summary(self,printmethod=None): printmethod = printmethod or self.debug if not self.diskdrives: printmethod('No disk drives to print?') return disklist = copy.copy(self.diskdrives) buf = (disklist.pop()).get_summary() for disk in disklist: buf += disk.get_summary(printheader=False) printmethod(buf) def print_partition_summary(self,printmethod=None): printmethod = printmethod or self.debug if not self.disk_partitions: printmethod('No disk partitions to print?') return partlist = copy.copy(self.disk_partitions) buf = (partlist.pop()).get_summary() for part in partlist: buf += part.get_summary(printheader=False) printmethod(buf) def print_logicaldisk_summary(self,printmethod=None): printmethod = printmethod or self.debug if not self.logicaldisks: printmethod('No disk disk_partitions to print?') return disklist = copy.copy(self.logicaldisks) buf = (disklist.pop()).get_summary() for disk in disklist: buf += disk.get_summary(printheader=False) printmethod(buf) def update_disk_info(self , forceupdate=False): if self.diskdrives: if not forceupdate and (time.time() - self.diskdrives[0].last_updated) <= self.disk_update_interval: return self.debug('Fetching updated disk info...') self.diskdrives = [] self.disk_partitions = [] self.logicaldisks = [] self.diskdrives = self.get_updated_diskdrive_info() self.disk_partitions = self.get_updated_partition_info() self.logicaldisks = self.get_updated_logicaldisk_info() self.associate_diskdrives_to_partitions() self.associate_partitions_to_logicaldrives() def get_updated_diskdrive_info(self): ''' Populate self.diskdrives with WinInstanceDisk objects containing info parsed from wmic command. Since wmic doesn't seem to use delimeters this method attempts to derive the lengh of each column/header in order to parse out the info per disk. :pararm force: boolean. Will force an update, otherwise this method will wait a minimum of self.disk_update_interval before updating again. ''' #cmd = "wmic diskdrive get /format:textvaluelist.xsl" self.debug('Getting updated diskdrive info...') cmd = "wmic diskdrive list full" diskdrives = [] for disk_dict in self.get_parsed_wmic_command_output(cmd): try: diskdrives.append(WinInstanceDiskDrive(self,disk_dict)) except Exception, e: tb = self.tester.get_traceback() self.debug('Error attempting to create WinInstanceDiskDrive from following dict:') self.print_dict(dict=disk_dict) raise Exception(str(tb) + "\n Error attempting to create WinInstanceDiskDrive:" + str(e)) self.debug('get_updated_diskdrive_info, Done') return diskdrives def get_updated_partition_info(self): ''' Populate self.diskdrives with WinInstanceDisk objects containing info parsed from wmic command. Since wmic doesn't seem to use delimeters this method attempts to derive the lengh of each column/header in order to parse out the info per disk. :pararm force: boolean. Will force an update, otherwise this method will wait a minimum of self.disk_update_interval before updating again. ''' self.debug('Getting udpated partition info...') cmd = "wmic partition list brief /format:textvaluelist.xsl" disk_partitions = [] for part_dict in self.get_parsed_wmic_command_output(cmd): try: disk_partitions.append(WinInstanceDiskPartition(self,part_dict)) except Exception, e: tb = self.tester.get_traceback() self.debug('Error attempting to create WinInstanceDiskPartition from following dict:') self.print_dict(dict=part_dict) raise Exception(str(tb) + "\n Error attempting to create WinInstanceDiskPartition:" + str(e)) self.debug('get_updated_partition_info, Done') return disk_partitions def get_updated_logicaldisk_info(self): self.debug('Getting updated logicaldisk info...') cmd ='wmic logicaldisk list /format:textvaluelist.xsl' logicaldisks = [] for part_dict in self.get_parsed_wmic_command_output(cmd): try: logicaldisks.append(WinInstanceLogicalDisk(self,part_dict)) except Exception, e: tb = self.tester.get_traceback() self.debug('Error attempting to create WinInstanceLogicalDisk from following dict:') self.print_dict(dict=part_dict) raise Exception(str(tb) + "\n Error attempting to create WinInstanceLogicalDisk:" + str(e)) self.debug('get_updated_logicaldisk_info, Done') return logicaldisks def associate_diskdrives_to_partitions(self): for disk in self.diskdrives: disk.disk_partitions = [] for part in self.disk_partitions: if part.diskindex == disk.index: disk.disk_partitions.append(part) def associate_partitions_to_logicaldrives(self, verbose=False): for part in self.disk_partitions: drive_id = None part.logicaldisks = [] cmd = 'wmic partition where (DeviceID="Disk #' + str(part.diskindex) + \ ', Partition #' + str(part.index) + '") assoc /assocclass:Win32_LogicalDiskToPartition' output = self.sys(cmd, verbose=verbose, code=0) for line in output: if re.search('Win32_LogicalDisk.DeviceID',line): try: drive_id = str(line.split()[0].split('=')[1]).replace('"','').strip() except Exception, e: tb = self.tester.get_traceback() self.debug(str(tb)+ "\nError getting logical drive info:" + str(e)) if drive_id: for disk in self.logicaldisks: if re.match(disk.deviceid, drive_id): part.logicaldisks.append(disk) disk.partition = part break def get_cygwin_scsi_dev_for_windows_drive(self, windisk=None, drive_id=""): ''' param windisk: WinInstanceDiskType object. windisk.deviceid is used to look up the associated cygwin device param drive_id: String representing the deviceid. Can be used instead of passing a WinInstanceDiskType ''' windisk_classname = "" update = False retries = 2 if windisk: drive_id = windisk.deviceid windisk_classname = str(windisk.__class__).split('.').pop() #If this is a disk drive allow a retry which set the force update flag, otherwise don't force and retry if isinstance(windisk,WinInstanceDiskDrive): update = True if not drive_id: raise Exception('WinInstanceDiskType or string w/ device id not provided') self.debug('Attempting to get cygwin dev for windows drive:' + str(drive_id)) self.update_cygwin_windows_device_map() for retry in xrange(0, retries): for device in self.cygwin_dev_map: if re.search("dev", device): win_dev = str(self.cygwin_dev_map[device].split('\\').pop()).strip().upper() formated_drive_id = str(drive_id.split('\\').pop()).strip().upper() #self.debug('Attempt to match:"' + str(win_dev) + '" with "' + str(formated_drive_id) + '"') if formated_drive_id == win_dev: #self.debug('Found match') return device if update: self.update_cygwin_windows_device_map(force_update=True) else: break self.debug('WARNING: Could not find cygwin device for type:"' + str(windisk_classname) + '", deviceid:' +
0
920cd41b18f5cfb45f46c44ed707cebe682d4dd9
Python
str(drive_id)) return "" def get_parsed_wmic_command_output(self, wmic_command, verbose=False): ''' Attempts to parse a wmic command using "/format:textvaluelist.xsl" for key value format into a list of dicts. :param wmic_command: string representing the remote wmic command to be run :returns : list of dict(s) created from the parsed key value output of the command. Note keys will be in lowercase ''' self.debug('get_parsed_wmic_command_output, command:' + str(wmic_command)) ret_dicts = [] output = self.sys(wmic_command, verbose=verbose, code=0) newdict = {} for line in output: if not re.match(r"^\w",line): #If there is a blank line(s) then the previous object is complete if newdict: ret_dicts.append(newdict) newdict = {} else: splitline = line.split('=') key = str(splitline.pop(0)).lower() if len(splitline) > 1: value = "=".join(str(x) for x in splitline) else: if splitline: value = splitline.pop() else: value = '' newdict[key] = value return ret_dicts def get_logicaldisk_ids(self, forceupdate=False): ''' :param forceupdate: boolean, to force an update of logical disks detected on the guest. Otherwise updates are throttled to self.disk_update_interval :returns list of device ids (ie: [A:,C:,D:] ''' ret = [] self.update_disk_info(forceupdate=forceupdate) for disk in self.logicaldisks: ret.append(disk.deviceid) return ret def get_diskdrive_ids(self, drivelist=None, forceupdate=False): ''' :param forceupdate: boolean, to force an update of logical disks detected on the guest. Otherwise updates are throttled to self.disk_update_interval :returns list of device ids ie: ['\\.\PHYSICALDRIVE0','\\.\PHYSICALDRIVE1,'\\.\PHYSICALDRIVE2'] ''' ret = [] if not drivelist: self.update_disk_info(forceupdate=forceupdate) drivelist = self.diskdrives for disk in drivelist: ret.append(disk.deviceid) return ret def get_diskdrive_by_deviceid(self, deviceid): for disk in self.diskdrives: if disk.deviceid == deviceid: return disk def found(self, command, regex): """ Returns a Boolean of whether the result of the command contains the regex""" result = self.sys(command) for line in result: found = re.search(regex,line) if found: return True return False def assertFilePresent(self,filepath): ''' Raise exception if file not found at filepath on remote guest. dirs '\' need to be represented as '\\' ''' self.sys('dir ' + str(filepath), code=0) def assertCygwinFilePresent(self, filepath): self.cygwin_cmd('ls ' + str(filepath), code=0) def attach_volume(self, volume, dev=None, timeout=180, overwrite=False): ''' Method used to attach a volume to an instance and track it's use by that instance required - euvolume - the euvolume object being attached required - tester - the eucaops/nephoria object/connection for this cloud optional - dev - string to specify the dev path to 'request' when attaching the volume to optional - timeout - integer- time allowed before failing optional - overwrite - flag to indicate whether to overwrite head data of a non-zero filled volume upon attach for md5 ''' if not isinstance(volume, EuVolume): volume = EuVolume.make_euvol_from_vol(volume) return self.attach_euvolume(volume, dev=dev, timeout=timeout, overwrite=overwrite) def attach_euvolume(self, euvolume, dev=None, timeout=180, overwrite=False): ''' Method used to attach a volume to an instance and track it's use by that instance required - euvolume - the euvolume object being attached required - tester - the eucaops/nephoria object/connection for this cloud optional - dev - string to specify the dev path to 'request' when attaching the volume to optional - timeout - integer- time allowed before failing optional - overwrite - flag to indicate whether to overwrite head data of a non-zero filled volume upon attach for md5 ''' if not isinstance(euvolume, EuVolume): raise Exception("Volume needs to be of type euvolume, try attach_volume() instead?") self.debug('Disk drive summary before attach attempt:') self.print_logicaldisk_summary() self.print_diskdrive_summary() self.debug("Attempting to attach volume:"+str(euvolume.id)+" to instance:" +str(self.id)+" to dev:"+ str(dev)) #grab a snapshot of our devices before attach for comparison purposes diskdrive_list_before = self.get_diskdrive_ids() use_serial = False for disk in self.diskdrives: if re.search('vol-', disk.serialnumber): use_serial = True break attached_dev = None start= time.time() elapsed = 0 if dev is None: #update our block device prefix dev = self.get_free_scsi_dev() if (self.tester.attach_volume(self, euvolume, dev, pause=10,timeout=timeout)): if euvolume.attach_data.device != dev: raise Exception('Attached device:' + str(euvolume.attach_data.device) + ", does not equal requested dev:" + str(dev)) #Find device this volume is using on guest... euvolume.guestdev = None while (not euvolume.guestdev and elapsed < timeout): #Since all hypervisors may not support serial number info, check for an incremental diff in the # list of physical diskdrives on this guest. self.debug("Checking for volume attachment on guest, elapsed time("+str(elapsed)+")") diskdrive_list_after = self.get_diskdrive_ids(forceupdate=True) self.print_logicaldisk_summary() self.print_diskdrive_summary() self.debug("dev_list_after:"+" ".join(diskdrive_list_after)) diff =list( set(diskdrive_list_after) - set(diskdrive_list_before) ) if len(diff) > 0: self.debug('Got Diff in drives:' + str(diff)) for disk in self.diskdrives: if re.search('vol-', disk.serialnumber): use_serial = True if euvolume.id == disk.ebs_volume: attached_dev = disk.deviceid euvolume.guestdev = attached_dev self.debug("Volume:"+str(euvolume.id)+" guest device by serialnumber:"+str(euvolume.guestdev)) break if not use_serial: attached_dev = str(diff[0]) euvolume.guestdev = attached_dev.strip() self.debug("Volume:"+str(euvolume.id)+"found guest device by diff:"+str(euvolume.guestdev)) if attached_dev: euvolume.guestdev = attached_dev attached_vol = self.get_volume_from_attached_list_by_id(euvolume.id) self.attached_vols.append(euvolume) self.debug(euvolume.id+": Requested dev:"+str(euvolume.attach_data.device)+", attached to guest device:"+str(euvolume.guestdev)) break elapsed = int(time.time() - start) time.sleep(2) if not euvolume.guestdev or not attached_dev: raise Exception('Device not found on guest after '+str(elapsed)+' seconds') else: self.debug('Failed to attach volume:'+str(euvolume.id)+' to instance:'+self.id) raise Exception('Failed to attach volume:'+str(euvolume.id)+' to instance:'+self.id) if (attached_dev is None): self.debug("List after\n"+" ".join(diskdrive_list_after)) raise Exception('Volume:'+str(euvolume.id)+' attached, but not found on guest'+str(self.id)+' after '+str(elapsed)+' seconds?') #Store the md5sum of this diskdrive in the euvolume... disk = self.get_diskdrive_by_deviceid(attached_dev) euvolume.md5len = 1024 euvolume.md5 = self.get_dev_md5(devpath=disk.cygwin_scsi_drive, length=euvolume.md5len) #update the volume and instances information about the attachment... self.update_volume_guest_info(volume=euvolume,md5=euvolume.md5, md5len=euvolume.md5len, guestdev=euvolume.guestdev) self.debug('Success attaching volume:'+str(euvolume.id)+' to instance:'+self.id + ', cloud dev:'+str(euvolume.attach_data.device)+', attached dev:'+str(attached_dev) + ", elapsed:" + str(elapsed)) try: self.rescan_disks(timeout=20) except Exception, e: self.debug('Warning. Error while trying to rescan disks after attaching volume. Error: ' + str(e)) euvolume.printself(printmethod=self.debug) disk.print_self() return attached_dev def get_guest_dev_for_volume(self, volume, forceupdate=False): use_serial = False self.update_disk_info(forceupdate=forceupdate) for disk in self.diskdrives: if re.search('vol-', disk.serialnumber): use_serial = True break if not isinstance(volume, EuVolume): volume = EuVolume.make_euvol_from_vol(volume=volume, tester=self.tester) def get_disk_drive_by_id(self, deviceid): self.update_system_info() for disk in self.diskdrives: if disk.deviceid == deviceid: return disk return None def get_guestdevs_inuse_by_vols(self): retlist = [] for vol in self.attached_vols: retlist.append(vol.guestdev) return retlist def get_free_scsi_dev(self, prefix=None,maxdevs=16): ''' The volume attach command requires a cloud level device name that is not currently associated with a volume Note: This is the device name from the clouds perspective, not necessarily the guest's This method attempts to find a free device name to use in the command optional - prefix - string, pre-pended to the the device search string optional - maxdevs - number use to specify the max device names to iterate over.Some virt envs have a limit of 16 devs. ''' d='e' in_use_cloud = "" in_use_guest = "" dev = None if prefix is None: prefix = self.block_device_prefix cloudlist=self.tester.get_volumes(attached_instance=self.id) for x in xrange(0,maxdevs): inuse=False #double up the letter identifier to avoid exceeding z if d == 'z': prefix= prefix+'e' dev = "/dev/"+prefix+str(d) for avol in self.attached_vols: if avol.attach_data.device == dev: inuse = True in_use_guest += str(avol.id)+", " continue #Check to see if the cloud has a conflict with this device name... for vol in cloudlist: vol.update() if (vol.attach_data is not None) and (vol.attach_data.device == dev): inuse = True in_use_cloud += str(vol.id)+", " continue if inuse is False: self.debug("Instance:"+str(self.id)+" returning available cloud scsi dev:"+str(dev)) return str(dev) else: d = chr(ord('e') + x) #increment the letter we append to the device string prefix dev = None if dev is None: raise Exception("Could not find a free scsi dev on instance:"+self.id+", maxdevs:"+str(maxdevs)+"\nCloud_devs:"+str(in_use_cloud)+"\nGuest_devs:"+str(in_use_guest)) def detach_euvolume(self, euvolume, waitfordev=True, timeout=180): ''' Method used to detach detach a volume to an instance and track it's use by that instance required - euvolume - the euvolume object being deattached waitfordev - boolean to indicate whether or no to poll guest instance for local device to be removed optional - timeout - integer seconds to wait before timing out waiting for the volume to detach ''' start = time.time() elapsed = 0 found = True for vol in self.attached_vols: if vol.id == euvolume.id: dev = vol.guestdev if (self.tester.detach_volume(euvolume,timeout=timeout)): if waitfordev: self.debug("Cloud has detached" + str(vol.id) + ", Wait for device:"+str(dev)+" to be removed on guest...") while (elapsed < timeout): diskdrive_ids = [] try: disk_drives = self.get_updated_diskdrive_info() for disk in disk_drives: if dev == disk.deviceid: found = True break found = False self.debug('Diskdrive associated with ' + str(vol.id) + ' has been removed from guest.') #if device is not present remove it self.attached_vols.remove(vol) except Exception, de: self.debug('Warning, error getting diskdrive id during detach:' + str(de)) if not found: try: self.rescan_disks(timeout=20) except Exception, re: self.debug('Warning: Error while trying to rescan disks after detaching volume:' + str(re)) try: self.update_disk_info() except Exception, ue: self.debug('Warning: Error while trying to update disk info:' + str(ue)) try: self.print_diskdrive_summary() except: pass self.debug('Volume:' + str(vol.id) + ', detached, and no longer found on guest at:' + str(dev)) vol.set_volume_detached_tags() return True time.sleep(10) elapsed = int(time.time()-start) diskdrive_ids = self.get_diskdrive_ids(drivelist=disk_drives) self.debug('Current disk drives on guest:' + ",".join(str(x) for x in diskdrive_ids)) self.debug("Waiting for device '"+str(dev)+"' on guest to be removed.Elapsed:"+str(elapsed)) else: self.attached_vols.remove(vol) vol.set_volume_detached_tags() return True else: raise Exception("Volume("+str(vol.id)+") failed to detach from device("+str(dev)+") on ("+str(self.id)+")") raise Exception("Detach Volume("+str(euvolume.id)+") not found on ("+str(self.id)+")") return False def check_hostname(self): if not hasattr(self, 'system_info'): self.update_system_info() if hasattr(self, 'system_info') and hasattr(self.system_info, 'host_name'): if self.id.upper() == self.system_info.host_name.upper(): self.debug('Hostname:' + str(self.id) + ", instance.id:" + str(self.system_info.host_name)) else: raise Exception('check_hostname failed: hostname:' + str(self.system_info.host_name).upper() + " != id:" + str(self.id).upper()) else: raise Exception('check_hostname failed: System_info.hostname not populated') def get_process_list_brief(self): ''' Returns a list of dicts representing the processes running on the remote guest. Each service is represented by a dict containing information about the service. ''' cmd = "wmic process list brief /format:textvaluelist.xsl" return self.get_parsed_wmic_command_output(cmd) def get_process_list_full(self): ''' Returns a list of dicts representing the processes running on the remote guest. Each service is represented by a dict containing information about the service. ''' cmd = "wmic process list full" return self.get_parsed_wmic_command_output(cmd) def get_process_by_name(self,process_name): ''' Attempts to lookup a service on the remote guest. param service_name: string. The name of the service to get info returns a dict representing the information returned from the remote guest ''' cmd = 'wmic process ' + str(process_name) + ' get /format:textvaluelist.xsl' result = self.get_parsed_wmic_command_output(cmd) if result: return result[0] def get_services_list_brief(self): ''' Returns a list of dicts representing the services from the remote guest. Each service is represented by a dict containing information about the service. ''' cmd = 'wmic service list brief /format:textvaluelist.xsl' return self.get_parsed_wmic_command_output(cmd) def get_services_list_full(self): ''' Returns a list of dicts representing the services from the remote guest. Each service is represented by a dict containing information about the service. ''' cmd = 'wmic service list full' return self.get_parsed_wmic_command_output(cmd) def get_service_by_name(self,service_name): ''' Attempts to lookup a service on the remote guest. param service_name: string. The name of the service to get info returns a dict representing the information returned from the remote guest ''' cmd = 'wmic service ' + str(service_name) + ' get /format:textvaluelist.xsl' result = self.get_parsed_wmic_command_output(cmd) if result: return result[0] def get_memtotal_in_mb(self): return long(self.system_info.total_physical_memory.split()[0].replace(',','')) def get_memtotal_in_gb(self): return long(self.get_memtotal_in_mb()/1024) def check_ram_against_vmtype(self, pad=32): total_ram = self.get_memtotal_in_mb() self.debug('Ram check: vm_ram:' + str(self.vmtype_info.ram) + "mb vs memtotal:" + str(total_ram) + "mb. Diff:" + str(self.vmtype_info.ram - total_ram) + "mb, pad:" + str(pad) + "mb") if not ((self.vmtype_info.ram - total_ram) <= pad): raise Exception('Ram check failed. vm_ram:' + str(self.vmtype_info.ram) + " vs memtotal:" + str(total_ram) + ". Diff is greater than allowed pad:" + str(pad) + "mb") else: self.debug('check_ram_against_vmtype, passed') def check_ephemeral_against_vmtype(self): gb = self.gigabyte size = self.vmtype_info.disk ephemeral_dev = self.get_ephemeral_dev() block_size = self.get_blockdev_size_in_bytes(ephemeral_dev) gbs = block_size / gb self.debug('Ephemeral check: ephem_dev:' + str(ephemeral_dev) + ", bytes:" + str(block_size) + ", gbs:" + str(gbs) + ", vmtype size:" + str(size)) if gbs != size: raise Exception('Ephemeral check failed. ' + str(ephemeral_dev) + ' Blocksize: ' + str(gbs) + "gb (" + str(block_size) + "bytes)" + ' != vmtype size:' +str(size) + "gb") else: self.debug('check_ephemeral_against_vmtype, passed') return ephemeral_dev def get_ephemeral_dev(self): """ Attempts to find the block device path on this instance :return: string representing path to ephemeral block device """ ephem_name = None dev_prefixs = ['s','v','xd','xvd'] if not self.root_device_type == 'ebs': try: self.assertFilePresent('/dev/' + str(self.rootfs_device)) return self.rootfs_device except: ephem_name = 'da' else: ephem_name = 'db' devs = self.get_dev_dir() for prefix in dev_prefixs: if str(prefix+ephem_name) in devs: return str('/dev/'+prefix+ephem_name) raise Exception('Could not find ephemeral device?') def cygwin_cmd(self, cmd, timeout=120, verbose=False, code=None): cmd = self.get_cygwin_path() + '\\bin\\bash.exe --login -c "' + str(cmd) + '"' return self.sys(cmd,timeout=timeout, verbose=verbose, code=code) def get_dev_md5(self, devpath, length, timeout=60): self.assertCygwinFilePresent(devpath) if length == 0: md5 = str(self.cygwin_cmd('md5sum ' + devpath, timeout=timeout)[0]).split(' ')[0].strip() else: md5 = str(self.cygwin_cmd("head -c " + str(length) + " " + str(devpath) + " | md5sum")[0]).split(' ')[0].strip() return md5 def update_cygwin_windows_device_map(self, prefix='/dev/*', force_update=False): cygwin_dev_map = {} if not force_update: if self.cygwin_dev_map: if time.time() - self.cygwin_dev_map['last_updated'] <= 30: cygwin_dev_map = self.cygwin_dev_map if not cygwin_dev_map: self.debug('Updating cygwin to windows device mapping...') output = self.cygwin_cmd("for DEV in " + prefix + " ; do printf $DEV=$(cygpath -w $DEV); echo ''; done", verbose=False, code=0) for line in output: if re.match(prefix, line): split = line.split('=') key = split.pop(0) if split: value = split.pop() else: value = '' cygwin_dev_map[key]=value cygwin_dev_map['last_updated'] = time.time() self.cygwin_dev_map = cygwin_dev_map self.debug('Updated cygwin to windows device mapping') return cygwin_dev_map def rescan_disks(self, timeout=20): ''' Attempts to rescan disks on the guest. This may help expedite updates/discovery when attaching/detaching volumes to the guest. This has also been found to hang post device removal so is used with a 20 second command timeout as the default. param timeout: integer. Seconds to wait on command before failing ''' scriptname = 'eutester_diskpart_script' self.sys('(echo rescan && echo list disk ) > ' + str(scriptname), code=0) self.sys('diskpart /s ' + str(scriptname), code=0, timeout=timeout) def get_diskdrive_for_volume(self, volume): if not self.is_volume_attached_to_this_instance(volume): return None ret_disk = None for disk in self.diskdrives: disk.update_ebs_info() if disk.ebs_volume == volume.id: ret_disk = disk if not ret_disk: ret_disk = self.find_diskdrive_for_volume_by_serial_number(volume, force_check=True) if not ret_disk: if hasattr(volume,'md5') and volume.md5: ret_disk = self.find_diskdrive_for_volume_by_md5(volume, force_check=True) return ret_disk def find_diskdrive_for_volume_by_md5(self, volume, md5=None, length=None, force_check=False): if not force_check and not self.is_volume_attached_to_this_instance(volume): return None if not isinstance(volume, EuVolume): volume = EuVolume.make_euvol_from_vol(volume=volume,tester=self.tester) md5 = md5 or volume.md5 if not md5: return None length = length or volume.md5len for disk in self.diskdrives: if disk.cygwin_scsi_drive: disk_md5 = self.get_dev_md5(disk.cygwin_scsi_drive, length=length) if disk_md5 == md5: volume.guestdev = disk.deviceid volume.md5 = disk_md5 volume.md5len = length disk.ebs_volume = volume.id return disk return None def find_diskdrive_for_volume_by_serial_number(self, volume, serial_number=None, force_check=False): ''' Attempt to iterate through all the diskdrives were aware of. If a diskdrive is found with a serial_number associated with the volume, return that diskdrive obj.. example serial number format: vol-81C13EA4-dev-sdg :param volume: volume obj to use for deriving the serial_number :param serial_number: string. Optional. The string representing the serial # to match. :returns WinInstanceDiskDrive if found, else None ''' if not force_check and not self.is_volume_attached_to_this_instance(volume): return None if not serial_number: serial_number = volume.id + volume.attach_data.device.replace('/','-') for disk in self.diskdrives: if disk.serialnumber == serial_number: return disk return None def is_volume_attached_to_this_instance(self, volume): ''' Attempts to look up volume state per cloud to confirm the cloud believe the state of this volume is attached to this instance. This does not verify the guest/hypervisor also belives the volume is attached. :param volume: volume obj. :returns boolean ''' volume.update() if hasattr(volume, 'attach_data') and volume.attach_data and (volume.attach_data.instance_id == self.id): self.debug('Volume:' + str(volume.id) + " is attached to this instance: " + str(self.id) + " per cloud perspective") return True else: self.debug('Volume:' + str(volume.id) + " is NOT attached to this instance: " + str(self.id) + " per cloud perspective") return False def update_volume_guest_info(self, volume, md5=None, md5len=None, guestdev=None): self.debug("{0} update_volume_guest_info: {1} {2}" .format(termline, volume, termline)) if not self.is_volume_attached_to_this_instance(volume): raise Exception('Volume not attached to this instance') disk = None if not self.get_volume_from_attached_list_by_id(volume.id): self.attached_vols.append(volume) volume.guestdev = guestdev or volume.guestdev if md5: if not md5len: raise Exception('Must provide md5len if providing the md5') volume.md5 = md5 volume.md5len = md5len else: disk = self.get_diskdrive_for_volume(volume) if not disk: raise Exception('Could not find diskdrive for volume when attempting to update volume guest info:' + str(volume)) volume.md5len = md5len or 1024 volume.md5 = self.get_dev_md5(disk.cygwin_scsi_drive, volume.md5len) if not guestdev: volume.guestdev = disk.deviceid disk = disk or self.get_diskdrive_for_volume(volume) disk.update_ebs_info() volume.update_volume_attach_info_tags(md5=volume.md5, md5len=volume.md5len, instance_id=self.id, guestdev=volume.guestdev) return volume def get_unsynced_volumes(self, check_md5=True): ''' Description: Returns list of volumes which are: -in a state the cloud believes the vol is no longer attached -the attached device has changed, or is not found. If all euvols are shown as attached to this instance, and the last known local dev is present and/or a local device is found with matching md5 checksum then the list will return 'None' as all volumes are successfully attached and state is in sync. By default this method will iterate through all the known euvolumes attached to this euinstance. A subset can be provided in the list argument 'euvol_list'. Returns a list of euvolumes for which a corresponding guest device could not be found, or the cloud no longer believes is attached. :param euvol_list: - optional - euvolume object list. Defaults to all self.attached_vols :param md5length: - optional - defaults to the length given in each euvolume. Used to calc md5 checksum of devices :param timerpervolume: -optional - time to wait for device to appear, per volume before failing :param min_polls: - optional - minimum iterations to check guest devs before failing, despite timeout :param check_md5: - optional - find devices by md5 comparision. Default is to only perform this check when virtio_blk is in use. ''' bad_list = [] retdict = self.sync_attached_volumes_with_clouds_view() bad_list.extend(retdict['badvols']) return bad_list def reboot_instance_and_verify(self, waitconnect=60, timeout=600, wait_for_ports=180, connect=True, checkvolstatus=False, pad=5, uptime_retries=3): ''' Attempts to reboot an instance and verify it's state post reboot. waitconnect-optional-integer representing seconds to wait before attempting to connect to instance after reboot timeout-optional-integer, seconds. If a connection has failed, this timer is used to determine a retry connect- optional - boolean to indicate whether an ssh session should be established once the expected state has been reached checkvolstatus - optional -boolean to be used to check volume status post start up ''' msg="" newuptime = None attempt = 0 def get_safe_uptime(): uptime = None try: uptime = self.get_uptime() except: pass return uptime self.debug('Attempting to reboot instance:'+str(self.id)+', check attached volume state first') uptime = self.tester.wait_for_result( get_safe_uptime, None, oper=operator.ne) elapsed = 0 start = time.time() if checkvolstatus: #update the md5sums per volume before reboot bad_vols=self.get_unsynced_volumes() if bad_vols != []: for bv in bad_vols: self.debug(str(self.id)+'Unsynced volume found:'+str(bv.id)) raise Exception(str(self.id)+"Could not reboot using checkvolstatus flag due to unsync'd volumes") self.debug('Rebooting now...') self.reboot() time.sleep(waitconnect) try: self.poll_for_ports_status(ports=[3389,5589], timeout=wait_for_ports) except: self.debug('Failed to poll winrm and rdp ports after ' + str(wait_for_ports) + ' seconds, try to connect anyways...') timeout=timeout - int(time.time()-start) while (elapsed < timeout): self.connect_to_instance(timeout=timeout) #Wait for the system to provide a valid response for uptime, early connections may not newuptime = self.tester.wait_for_result( get_safe_uptime, None, oper=operator.ne) elapsed = int(time.time()-start) #Check to see if new uptime is at least 'pad' less than before, allowing for some pad if (newuptime - (uptime+elapsed)) > pad: err_msg = "Instance uptime does not represent a reboot. Orig:"+str(uptime)+\ ", New:"+str(newuptime)+", elapsed:"+str(elapsed)+"/"+str(timeout) if elapsed > timeout: raise Exception(err_msg) else: self.debug(err_msg) else: self.debug("Instance uptime indicates a reboot. Orig:"+str(uptime)+\ ", New:"+str(newuptime)+", elapsed:"+str(elapsed)) break if checkvolstatus: badvols= self.get_unsynced_volumes() if badvols != []: for vol in badvols: msg = msg+"\nVolume:"+vol.id+" Local Dev:"+vol.guestdev raise Exception("Missing volumes post reboot:"+str(msg)+"\n") self.debug(self.id+" reboot_instance_and_verify Success") def get_uptime(self): if not hasattr(self, 'system_info'): self.update_system_info() if hasattr(self.system_info, 'system_boot_time'): return self._get_uptime_from_system_boot_time() elif hasattr(self.system_info, 'system_up_time'): return self._get_uptime_from_system_up_time() else: tb = self.tester.get_traceback() raise Exception(str(tb) + '\nCould not get system boot or up time from system_info') def _get_uptime_from_system_boot_time(self): #11/18/2013, 3:15:39 PM if not hasattr(self, 'system_info'): self.update_system_info() splitdate = self.system_info.system_boot_time.split() datestring = splitdate[0] timestring = splitdate[1] ampm = splitdate[2] month, day, year = datestring.replace(',',"").split('/') hours, minutes, seconds = timestring.split(':') if ampm == 'PM': hours = int(hours) + 12 datetimestring = str(year) + " " + \ str(month) + " " + \ str(day) + " " + \ str(hours) + " " + \ str(minutes) + " " + \ str(seconds) dt = datetime.strptime(datetimestring, "%Y %m %d %H %M %S") return int(time.time() - time.mktime(dt.timetuple())) def _get_uptime_from_system_up_time(self): #0 Days, 0 Hours, 6 Minutes, 39 Seconds if not hasattr(self, 'system_info'): self.update_system_info() uptime_string = self.system_info.system_up_time days = 0 hours = 0 minutes = 0 seconds = 0 split = uptime_string.split(',') for part in split: time_string = "" if re.search('Days', part, re.IGNORECASE): time_string = str(part.split()[0]).strip() days = int(time_string or 0) elif re.search('Hours', part, re.IGNORECASE): time_string = str(part.split()[0]).strip() hours = int(time_string or 0) elif re.search('Minutes', part, re.IGNORECASE): time_string = str(part.split()[0]).strip() minutes = int(time_string or 0) elif re.search('Seconds', part, re.IGNORECASE): time_string = str(part.split()[0]).strip() seconds = int(time_string or 0) self.debug("Days:" +str(days)+', Hours:'+ str(hours) + ", Minutes:" + str(minutes) + ", Seconds:" + str(seconds)) uptime = (days * 86400) + (hours * 3600) + (minutes * 60) + seconds return uptime def stop_instance_and_verify(self, timeout=200, state='stopped', failstate='terminated', check_vols=True): ''' Attempts to stop instance and verify the state has gone to stopped state :param timeout; -optional-time to wait on instance to go to state 'state' before failing :param state: -optional-the expected state to signify success, default is stopped :param failstate: -optional-a state transition that indicates failure, default is terminated ''' self.debug(self.id+" Attempting to stop instance...") start = time.time() elapsed = 0 self.stop() while (elapsed < timeout): time.sleep(2) self.update() if self.state == state: break if self.state == failstate: raise Exception(str(self.id) + " instance went to state:" + str(self.state) + " while stopping") elapsed = int(time.time()- start) if elapsed % 10 == 0 : self.debug(str(self.id) + " wait for stop, in state:" + str(self.state) + ",time remaining:" + str(elapsed) + "/" + str(timeout) ) if self.state != state: raise Exception(self.id + " state: " + str(self.state) + " expected:" + str(state) + ", after elapsed:" + str(elapsed)) if check_vols: for volume in self.attached_vols: volume.update if volume.status != 'in-use': raise Exception(str(self.id) + ', Volume ' + str(volume.id) + ':' + str(volume.status) + ' state did not remain in-use ' 'during stop') self.debug(self.id + " stop_instance_and_verify Success") def start_instance_and_verify(self, timeout=300, state = 'running', failstates=['terminated'], failfasttime=30, connect=True, checkvolstatus=True): ''' Attempts to start instance and verify state, and reconnects ssh session :param timeout: -optional-time to wait on instance to go to state 'state' before failing :param state: -optional-the expected state to signify success, default is running :param failstate: -optional-a state transition that indicates failure, default is terminated :param connect: -optional - boolean to indicate whether an ssh session should be established once the expected state has been reached :param checkvolstatus: -optional -boolean to be used to check volume status post start up ''' self.debug(self.id+" Attempting to start instance...") if checkvolstatus: for volume in self.attached_vols: volume.update if checkvolstatus: if volume.status != 'in-use': raise Exception(str(self.id) + ', Volume ' + str(volume.id) + ':' + str(volume.status) + ' state did not remain in-use during stop' ) self.debug("\n"+ str(self.id) + ": Printing Instance 'attached_vol' list:\n") self.tester.show_volumes(self.attached_vols) msg="" start = time.time() elapsed = 0 self.update() #Add fail fast states... if self.state == 'stopped': failstates.extend(['stopped','stopping']) self.start() while (elapsed < timeout): elapsed = int(time.time()- start) self.update() self.debug(str(self.id) + " wait for start, in state:" + str(self.state) + ",time remaining:" + str(elapsed) + "/"+str(timeout) ) if self.state == state: break if elapsed >= failfasttime: for failstate in failstates: if self.state == failstate: raise Exception(str(self.id) + " instance went to state:" + str(self.state) + " while starting") time.sleep(10) if self.state != state: raise Exception(self.id + " not in " + str(state) + " state after elapsed:" + str(elapsed)) else: self.debug(self.id + " went to state:" + str(state)) if connect: self.connect_to_instance(timeout=timeout) if checkvolstatus: badvols= self.get_unsynced_volumes(check_md5=True) if badvols != []: for vol in badvols: msg = msg + "\nVolume:" + vol.id + " Local Dev:" +\ vol.guestdev raise Exception("Missing volumes post reboot:" + str(msg) + "\n") self.debug(self.id+" start_instance_and_verify Success")
1
33867677611ceb757f6973eb70368c9f75f3ce92
Python
"# system\nimport os\nimport numpy as np\nimport random\nimport copy\nimport time\n\n# ROS\nimport r(...TRUNCATED)
0
33867677611ceb757f6973eb70368c9f75f3ce92
Python
"cm wide\n\n self.state.grasp_data = grasp_data\n self.visualize_grasp(grasp_data)\n\n(...TRUNCATED)
1
33867677611ceb757f6973eb70368c9f75f3ce92
Python
"GraspsResult(result)\n\n if not graspFound:\n rospy.loginfo(\"no grasp found, ret(...TRUNCATED)
2
bd179fda18551d4f3d8a4d695a9da38ee607ef1d
Python
"import datetime\nimport json\n\nfrom dateutil import parser\nimport mock\nfrom python_http_client.e(...TRUNCATED)
0
bd179fda18551d4f3d8a4d695a9da38ee607ef1d
Python
"HDR_RPT_POSITIVE\", hdr_record_pos.genomic_report_state_str)\n self.assertEqual(int(hdr_reco(...TRUNCATED)
1
addf92a3d4060fa9464a802a4a4378cf9eeadde4
Python
"# -*- coding: utf-8 -*-\n# This file is auto-generated, don't edit it. Thanks.\nfrom Tea.model impo(...TRUNCATED)
0
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
108