Coverage Report

Created: 2026-08-13 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/netcdf-c/libnczarr/zsync.c
Line
Count
Source
1
/*********************************************************************
2
 *   Copyright 1993, UCAR/Unidata
3
 *   See netcdf/COPYRIGHT file for copying and redistribution conditions.
4
 *********************************************************************/
5
6
#include "zincludes.h"
7
#include "zfilter.h"
8
#include <stddef.h>
9
#include "ncutil.h"
10
11
#ifndef nulldup
12
#define nulldup(x) ((x)?strdup(x):(x))
13
#endif
14
15
#undef FILLONCLOSE
16
17
/*mnemonics*/
18
#define DICTOPEN '{'
19
#define DICTCLOSE '}'
20
21
/* Forward */
22
static int ncz_collect_dims(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NCjson** jdimsp);
23
static int ncz_sync_var(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int isclose);
24
25
static int download_jatts(NC_FILE_INFO_T* file, NC_OBJ* container, const NCjson** jattsp, const NCjson** jtypesp);
26
static int zconvert(const NCjson* src, nc_type typeid, size_t typelen, int* countp, NCbytes* dst);
27
static int computeattrinfo(const char* name, const NCjson* jtypes, nc_type typehint, int purezarr, NCjson* values,
28
    nc_type* typeidp, size_t* typelenp, size_t* lenp, void** datap);
29
static int parse_group_content(const NCjson* jcontent, NClist* dimdefs, NClist* varnames, NClist* subgrps);
30
static int parse_group_content_pure(NCZ_FILE_INFO_T*  zinfo, NC_GRP_INFO_T* grp, NClist* varnames, NClist* subgrps);
31
static int define_grp(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp);
32
static int define_dims(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* diminfo);
33
static int define_vars(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* varnames);
34
static int define_var1(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, const char* varname);
35
static int define_subgrps(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* subgrpnames);
36
static int searchvars(NCZ_FILE_INFO_T*, NC_GRP_INFO_T*, NClist*);
37
static int searchsubgrps(NCZ_FILE_INFO_T*, NC_GRP_INFO_T*, NClist*);
38
static int locategroup(NC_FILE_INFO_T* file, size_t nsegs, NClist* segments, NC_GRP_INFO_T** grpp);
39
static int createdim(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, const char* name, size64_t dimlen, NC_DIM_INFO_T** dimp);
40
static int parsedimrefs(NC_FILE_INFO_T*, NClist* dimnames,  size64_t* shape, NC_DIM_INFO_T** dims, int create);
41
static int decodeints(const NCjson* jshape, size64_t* shapes);
42
static int computeattrdata(nc_type typehint, nc_type* typeidp, const NCjson* values, size_t* typelenp, size_t* lenp, void** datap);
43
static int computedimrefs(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int purezarr, int xarray, int ndims, NClist* dimnames, size64_t* shapes, NC_DIM_INFO_T** dims);
44
static int json_convention_read(const NCjson* jdict, NCjson** jtextp);
45
static int ncz_validate(NC_FILE_INFO_T* file);
46
static int insert_attr(NCjson* jatts, NCjson* jtypes, const char* aname, NCjson* javalue, const char* atype);
47
static int insert_nczarr_attr(NCjson* jatts, NCjson* jtypes);
48
static int upload_attrs(NC_FILE_INFO_T* file, NC_OBJ* container, NCjson* jatts);
49
static int getnczarrkey(NC_OBJ* container, const char* name, const NCjson** jncxxxp);
50
static int downloadzarrobj(NC_FILE_INFO_T*, struct ZARROBJ* zobj, const char* fullpath, const char* objname);
51
static int dictgetalt(const NCjson* jdict, const char* name, const char* alt, const NCjson** jvaluep);
52
53
/**************************************************/
54
/**************************************************/
55
/* Synchronize functions to make map and memory
56
be consistent. There are two sets of functions,
57
1) _sync_ - push memory to map (optionally create target)
58
2) _read_ - pull map data into memory
59
These functions are generally non-recursive. It is assumed
60
that the recursion occurs in the caller's code.
61
*/
62
63
/**
64
 * @internal Synchronize file metadata from memory to map.
65
 *
66
 * @param file Pointer to file info struct.
67
 *
68
 * @return ::NC_NOERR No error.
69
 * @author Dennis Heimbigner
70
 */
71
int
72
ncz_sync_file(NC_FILE_INFO_T* file, int isclose)
73
0
{
74
0
    int stat = NC_NOERR;
75
0
    NCjson* json = NULL;
76
77
0
    NC_UNUSED(isclose);
78
79
0
    LOG((3, "%s: file: %s", __func__, file->controller->path));
80
0
    ZTRACE(3,"file=%s isclose=%d",file->controller->path,isclose);
81
82
    /* Write out root group recursively */
83
0
    if((stat = ncz_sync_grp(file, file->root_grp, isclose)))
84
0
        goto done;
85
86
0
    stat = NCZMD_consolidate((NCZ_FILE_INFO_T*)file->format_file_info);
87
0
done:
88
0
    NCJreclaim(json);
89
0
    return ZUNTRACE(stat);
90
0
}
91
92
/**
93
 * @internal Synchronize dimension data from memory to map.
94
 *
95
 * @param grp Pointer to grp struct containing the dims.
96
 *
97
 * @return ::NC_NOERR No error.
98
 * @author Dennis Heimbigner
99
 */
100
static int
101
ncz_collect_dims(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NCjson** jdimsp)
102
0
{
103
0
    int stat=NC_NOERR;
104
0
    size_t i;
105
0
    NCjson* jdims = NULL;
106
0
    NCjson* jdimsize = NULL;
107
0
    NCjson* jdimargs = NULL;
108
109
0
    LOG((3, "%s: ", __func__));
110
0
    ZTRACE(3,"file=%s grp=%s",file->controller->path,grp->hdr.name);
111
112
0
    NCJnew(NCJ_DICT,&jdims);
113
0
    for(i=0; i<ncindexsize(grp->dim); i++) {
114
0
  NC_DIM_INFO_T* dim = (NC_DIM_INFO_T*)ncindexith(grp->dim,i);
115
0
  char slen[128];
116
117
0
        snprintf(slen,sizeof(slen),"%llu",(unsigned long long)dim->len);
118
0
  NCJnewstring(NCJ_INT,slen,&jdimsize);
119
120
  /* If dim is not unlimited, then write in the old format to provide
121
           maximum back compatibility.
122
        */
123
0
  if(dim->unlimited) {
124
0
      NCJnew(NCJ_DICT,&jdimargs);
125
0
      if((stat = NCJaddstring(jdimargs,NCJ_STRING,"size"))<0) {stat = NC_EINVAL; goto done;}
126
0
      if((stat = NCJappend(jdimargs,jdimsize))<0) {stat = NC_EINVAL; goto done;}
127
0
      jdimsize = NULL;
128
0
        if((stat = NCJaddstring(jdimargs,NCJ_STRING,"unlimited"))<0) {stat = NC_EINVAL; goto done;}
129
0
      if((stat = NCJaddstring(jdimargs,NCJ_INT,"1"))<0) {stat = NC_EINVAL; goto done;}
130
0
  } else { /* !dim->unlimited */
131
0
      jdimargs = jdimsize;
132
0
      jdimsize = NULL;
133
0
  }
134
0
  if((stat = NCJaddstring(jdims,NCJ_STRING,dim->hdr.name))<0) {stat = NC_EINVAL; goto done;}
135
0
  if((stat = NCJappend(jdims,jdimargs))<0) {stat = NC_EINVAL; goto done;}
136
0
    }
137
0
    if(jdimsp) {*jdimsp = jdims; jdims = NULL;}
138
0
done:
139
0
    NCJreclaim(jdims);
140
0
    return ZUNTRACE(THROW(stat));
141
0
}
142
143
/**
144
 * @internal Recursively synchronize group from memory to map.
145
 *
146
 * @param file Pointer to file struct
147
 * @param grp Pointer to grp struct
148
 *
149
 * @return ::NC_NOERR No error.
150
 * @author Dennis Heimbigner
151
 */
152
int
153
ncz_sync_grp(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, int isclose)
154
0
{
155
0
    int stat = NC_NOERR;
156
0
    size_t i;
157
0
    NCZ_FILE_INFO_T* zinfo = NULL;
158
0
    char version[1024];
159
0
    int purezarr = 0;
160
0
    NCZMAP* map = NULL;
161
0
    char* key = NULL;
162
0
    NCjson* json = NULL;
163
0
    NCjson* jgroup = NULL;
164
0
    NCjson* jdims = NULL;
165
0
    NCjson* jvars = NULL;
166
0
    NCjson* jsubgrps = NULL;
167
0
    NCjson* jnczgrp = NULL;
168
0
    NCjson* jsuper = NULL;
169
0
    NCjson* jtmp = NULL;
170
0
    NCjson* jatts = NULL;
171
0
    NCjson* jtypes = NULL;
172
173
0
    LOG((3, "%s: dims: %s", __func__, key));
174
0
    ZTRACE(3,"file=%s grp=%s isclose=%d",file->controller->path,grp->hdr.name,isclose);
175
176
0
    zinfo = file->format_file_info;
177
0
    map = zinfo->map;
178
179
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
180
181
    /* build Z2GROUP contents */
182
0
    NCJnew(NCJ_DICT,&jgroup);
183
0
    snprintf(version,sizeof(version),"%d",zinfo->format.zarr);
184
0
    if((stat = NCJaddstring(jgroup,NCJ_STRING,"zarr_format"))<0) {stat = NC_EINVAL; goto done;}
185
0
    if((stat = NCJaddstring(jgroup,NCJ_INT,version))<0) {stat = NC_EINVAL; goto done;}
186
187
    /* Write to map */
188
0
    NCZ_grpkey(grp,&key);
189
0
    if((stat=NCZMD_update_json_group(zinfo,key,(const NCjson*)jgroup))) goto done;
190
0
    nullfree(key); key = NULL;
191
192
0
    if(!purezarr) {
193
0
        if(grp->parent == NULL) { /* Root group */
194
      /* create superblock */
195
0
            snprintf(version,sizeof(version),NCZARR_FORMAT_VERSION_TEMPLATE, zinfo->format.nczarr);
196
0
      NCJnew(NCJ_DICT,&jsuper);
197
0
      if((stat = NCJinsertstring(jsuper,"version",version))<0) {stat = NC_EINVAL; goto done;}
198
0
  }
199
        /* Create dimensions dict */
200
0
        if((stat = ncz_collect_dims(file,grp,&jdims))) goto done;
201
202
        /* Create vars list */
203
0
        NCJnew(NCJ_ARRAY,&jvars);
204
0
        for(i=0; i<ncindexsize(grp->vars); i++) {
205
0
      NC_VAR_INFO_T* var = (NC_VAR_INFO_T*)ncindexith(grp->vars,i);
206
0
      if((stat = NCJaddstring(jvars,NCJ_STRING,var->hdr.name))<0) {stat = NC_EINVAL; goto done;}
207
0
        }
208
209
        /* Create subgroups list */
210
0
        NCJnew(NCJ_ARRAY,&jsubgrps);
211
0
        for(i=0; i<ncindexsize(grp->children); i++) {
212
0
      NC_GRP_INFO_T* g = (NC_GRP_INFO_T*)ncindexith(grp->children,i);
213
0
      if((stat = NCJaddstring(jsubgrps,NCJ_STRING,g->hdr.name))<0) {stat = NC_EINVAL; goto done;}
214
0
        }
215
        /* Create the "_nczarr_group" dict */
216
0
        NCJnew(NCJ_DICT,&jnczgrp);
217
        /* Insert the various dicts and arrays */
218
0
        if((stat = NCJinsert(jnczgrp,"dimensions",jdims))<0) {stat = NC_EINVAL; goto done;}
219
0
        jdims = NULL; /* avoid memory problems */
220
0
        if((stat = NCJinsert(jnczgrp,"arrays",jvars))<0) {stat = NC_EINVAL; goto done;}
221
0
        jvars = NULL; /* avoid memory problems */
222
0
        if((stat = NCJinsert(jnczgrp,"groups",jsubgrps))<0) {stat = NC_EINVAL; goto done;}
223
0
        jsubgrps = NULL; /* avoid memory problems */
224
0
    }
225
226
    /* Build the .zattrs object */
227
0
    assert(grp->att);
228
0
    NCJnew(NCJ_DICT,&jatts);
229
0
    NCJnew(NCJ_DICT,&jtypes);
230
0
    if((stat = ncz_sync_atts(file, (NC_OBJ*)grp, grp->att, jatts, jtypes, isclose))) goto done;
231
232
0
    if(!purezarr && jnczgrp != NULL) {
233
        /* Insert _nczarr_group */
234
0
        if((stat=insert_attr(jatts,jtypes,NCZ_V2_GROUP,jnczgrp,"|J0"))) goto done;
235
0
  jnczgrp = NULL;
236
0
    }
237
238
0
    if(!purezarr && jsuper != NULL) {
239
        /* Insert superblock */
240
0
        if((stat=insert_attr(jatts,jtypes,NCZ_V2_SUPERBLOCK,jsuper,"|J0"))) goto done;
241
0
  jsuper = NULL;
242
0
    }
243
244
    /* As a last mod to jatts, insert the jtypes as an attribute */
245
0
    if(!purezarr && jtypes != NULL) {
246
0
  if((stat = insert_nczarr_attr(jatts,jtypes))) goto done;
247
0
  jtypes = NULL;
248
0
    }
249
250
    /* Write out the .zattrs */
251
0
    nullfree(key);
252
0
    NCZ_grpkey(grp,&key);
253
0
    if((stat = NCZMD_update_json_attrs(zinfo, key, (const NCjson *)jatts))) goto done;
254
255
    /* Now synchronize all the variables */
256
0
    for(i=0; i<ncindexsize(grp->vars); i++) {
257
0
  NC_VAR_INFO_T* var = (NC_VAR_INFO_T*)ncindexith(grp->vars,i);
258
0
  if((stat = ncz_sync_var(file,var,isclose))) goto done;
259
0
    }
260
261
    /* Now recurse to synchronize all the subgrps */
262
0
    for(i=0; i<ncindexsize(grp->children); i++) {
263
0
  NC_GRP_INFO_T* g = (NC_GRP_INFO_T*)ncindexith(grp->children,i);
264
0
  if((stat = ncz_sync_grp(file,g,isclose))) goto done;
265
0
    }
266
267
0
done:
268
0
    NCJreclaim(jtmp);
269
0
    NCJreclaim(jsuper);
270
0
    NCJreclaim(json);
271
0
    NCJreclaim(jgroup);
272
0
    NCJreclaim(jdims);
273
0
    NCJreclaim(jvars);
274
0
    NCJreclaim(jsubgrps);
275
0
    NCJreclaim(jnczgrp);
276
0
    NCJreclaim(jtypes);
277
0
    NCJreclaim(jatts);
278
0
    nullfree(key);
279
0
    return ZUNTRACE(THROW(stat));
280
0
}
281
282
/**
283
 * @internal Synchronize variable meta data from memory to map.
284
 *
285
 * @param file Pointer to file struct
286
 * @param var Pointer to var struct
287
 * @param isclose If this called as part of nc_close() as opposed to nc_enddef().
288
 *
289
 * @return ::NC_NOERR No error.
290
 * @author Dennis Heimbigner
291
 */
292
static int
293
ncz_sync_var_meta(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int isclose)
294
0
{
295
0
    size_t i;
296
0
    int stat = NC_NOERR;
297
0
    NCZ_FILE_INFO_T* zinfo = NULL;
298
0
    char number[1024];
299
0
    NCZMAP* map = NULL;
300
0
    char* key = NULL;
301
0
    char* dimpath = NULL;
302
0
    NClist* dimrefs = NULL;
303
0
    NCjson* jvar = NULL;
304
0
    NCjson* jncvar = NULL;
305
0
    NCjson* jdimrefs = NULL;
306
0
    NCjson* jtmp = NULL;
307
0
    NCjson* jfill = NULL;
308
0
    NCjson* jatts = NULL;
309
0
    NCjson* jtypes = NULL;
310
0
    char* dtypename = NULL;
311
0
    int purezarr = 0;
312
0
    size64_t shape[NC_MAX_VAR_DIMS];
313
0
    NCZ_VAR_INFO_T* zvar = var->format_var_info;
314
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
315
    NClist* filterchain = NULL;
316
    NCjson* jfilter = NULL;
317
#endif
318
319
0
    ZTRACE(3,"file=%s var=%s isclose=%d",file->controller->path,var->hdr.name,isclose);
320
321
0
    zinfo = file->format_file_info;
322
0
    map = zinfo->map;
323
324
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
325
326
    /* Make sure that everything is established */
327
    /* ensure the fill value */
328
0
    if((stat = NCZ_ensure_fill_value(var))) goto done; /* ensure var->fill_value is set */
329
0
    assert(var->no_fill || var->fill_value != NULL);
330
    /* ensure the chunk cache */
331
0
    if((stat = NCZ_adjust_var_cache(var))) goto done;
332
    /* rebuild the fill chunk */
333
0
    if((stat = NCZ_ensure_fill_chunk(zvar->cache))) goto done;
334
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
335
    /* Build the filter working parameters for any filters */
336
    if((stat = NCZ_filter_setup(var))) goto done;
337
#endif
338
339
    /* Construct var path */
340
0
    if((stat = NCZ_varkey(var,&key)))
341
0
  goto done;
342
343
    /* Create the zarray json object */
344
0
    NCJnew(NCJ_DICT,&jvar);
345
346
    /* zarr_format key */
347
0
    snprintf(number,sizeof(number),"%d",zinfo->format.zarr);
348
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"zarr_format"))<0) {stat = NC_EINVAL; goto done;}
349
0
    if((stat = NCJaddstring(jvar,NCJ_INT,number))<0) {stat = NC_EINVAL; goto done;}
350
351
    /* Collect the shape vector */
352
0
    for(i=0;i<var->ndims;i++) {
353
0
  NC_DIM_INFO_T* dim = var->dim[i];
354
0
  shape[i] = dim->len;
355
0
    }
356
    /* but might be scalar */
357
0
    if(var->ndims == 0)
358
0
        shape[0] = 1;
359
360
    /* shape key */
361
    /* Integer list defining the length of each dimension of the array.*/
362
    /* Create the list */
363
0
    NCJnew(NCJ_ARRAY,&jtmp);
364
0
    if(zvar->scalar) {
365
0
  NCJaddstring(jtmp,NCJ_INT,"1");
366
0
    } else for(i=0;i<var->ndims;i++) {
367
0
  snprintf(number,sizeof(number),"%llu",shape[i]);
368
0
  NCJaddstring(jtmp,NCJ_INT,number);
369
0
    }
370
0
    if((stat = NCJinsert(jvar,"shape",jtmp))<0) {stat = NC_EINVAL; goto done;}
371
0
    jtmp = NULL;
372
373
    /* dtype key */
374
    /* A string or list defining a valid data type for the array. */
375
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"dtype"))<0) {stat = NC_EINVAL; goto done;}
376
0
    { /* Add the type name */
377
0
  int endianness = var->type_info->endianness;
378
0
  int atomictype = var->type_info->hdr.id;
379
0
  assert(atomictype > 0 && atomictype <= NC_MAX_ATOMIC_TYPE);
380
0
  if((stat = ncz_nctype2dtype(atomictype,endianness,purezarr,NCZ_get_maxstrlen((NC_OBJ*)var),&dtypename))) goto done;
381
0
  if((stat = NCJaddstring(jvar,NCJ_STRING,dtypename))<0) {stat = NC_EINVAL; goto done;}
382
0
  nullfree(dtypename); dtypename = NULL;
383
0
    }
384
385
    /* chunks key */
386
    /* The zarr format does not support the concept
387
       of contiguous (or compact), so it will never appear in the read case.
388
    */
389
    /* list of chunk sizes */
390
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"chunks"))<0) {stat = NC_EINVAL; goto done;}
391
    /* Create the list */
392
0
    NCJnew(NCJ_ARRAY,&jtmp);
393
0
    if(zvar->scalar) {
394
0
  NCJaddstring(jtmp,NCJ_INT,"1"); /* one chunk of size 1 */
395
0
    } else for(i=0;i<var->ndims;i++) {
396
0
  size64_t len = var->chunksizes[i];
397
0
  snprintf(number,sizeof(number),"%lld",len);
398
0
  NCJaddstring(jtmp,NCJ_INT,number);
399
0
    }
400
0
    if((stat = NCJappend(jvar,jtmp))<0) {stat = NC_EINVAL; goto done;}
401
0
    jtmp = NULL;
402
403
    /* fill_value key */
404
0
    if(var->no_fill) {
405
0
  NCJnew(NCJ_NULL,&jfill);
406
0
    } else {/*!var->no_fill*/
407
0
  int atomictype = var->type_info->hdr.id;
408
0
        if(var->fill_value == NULL) {
409
0
       if((stat = NCZ_ensure_fill_value(var))) goto done;
410
0
  }
411
        /* Convert var->fill_value to a string */
412
0
  if((stat = NCZ_stringconvert(atomictype,1,var->fill_value,&jfill))) goto done;
413
0
  assert(jfill->sort != NCJ_ARRAY);
414
0
    }
415
0
    if((stat = NCJinsert(jvar,"fill_value",jfill))<0) {stat = NC_EINVAL; goto done;}
416
0
    jfill = NULL;
417
418
    /* order key */
419
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"order"))<0) {stat = NC_EINVAL; goto done;}
420
    /* "C" means row-major order, i.e., the last dimension varies fastest;
421
       "F" means column-major order, i.e., the first dimension varies fastest.*/
422
    /* Default to C for now */
423
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"C"))<0) {stat = NC_EINVAL; goto done;}
424
425
    /* Compressor and Filters */
426
    /* compressor key */
427
    /* From V2 Spec: A JSON object identifying the primary compression codec and providing
428
       configuration parameters, or ``null`` if no compressor is to be used. */
429
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"compressor"))<0) {stat = NC_EINVAL; goto done;}
430
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
431
    filterchain = (NClist*)var->filters;
432
    if(nclistlength(filterchain) > 0) {
433
  struct NCZ_Filter* filter = (struct NCZ_Filter*)nclistget(filterchain,nclistlength(filterchain)-1);
434
        /* encode up the compressor */
435
        if((stat = NCZ_filter_jsonize(file,var,filter,&jtmp))) goto done;
436
    } else
437
#endif
438
0
    { /* no filters at all */
439
        /* Default to null */
440
0
        NCJnew(NCJ_NULL,&jtmp);
441
0
    }
442
0
    if(jtmp && (stat = NCJappend(jvar,jtmp))<0) {stat = NC_EINVAL; goto done;}
443
0
    jtmp = NULL;
444
445
    /* filters key */
446
    /* From V2 Spec: A list of JSON objects providing codec configurations,
447
       or null if no filters are to be applied. Each codec configuration
448
       object MUST contain a "id" key identifying the codec to be used. */
449
    /* A list of JSON objects providing codec configurations, or ``null``
450
       if no filters are to be applied. */
451
0
    if((stat = NCJaddstring(jvar,NCJ_STRING,"filters"))<0) {stat = NC_EINVAL; goto done;}
452
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
453
    if(nclistlength(filterchain) > 1) {
454
  size_t k;
455
  /* jtmp holds the array of filters */
456
  NCJnew(NCJ_ARRAY,&jtmp);
457
  for(k=0;k<nclistlength(filterchain)-1;k++) {
458
      struct NCZ_Filter* filter = (struct NCZ_Filter*)nclistget(filterchain,k);
459
      /* encode up the filter as a string */
460
      if((stat = NCZ_filter_jsonize(file,var,filter,&jfilter))) goto done;
461
      if((stat = NCJappend(jtmp,jfilter))<0) {stat = NC_EINVAL; goto done;}
462
  }
463
    } else
464
#endif
465
    /* no filters at all */
466
0
    NCJnew(NCJ_NULL,&jtmp);
467
0
    if((stat = NCJappend(jvar,jtmp))<0) {stat = NC_EINVAL; goto done;}
468
0
    jtmp = NULL;
469
470
    /* dimension_separator key */
471
    /* Single char defining the separator in chunk keys */
472
0
    if(zvar->dimension_separator != DFALT_DIM_SEPARATOR) {
473
0
  char sep[2];
474
0
  sep[0] = zvar->dimension_separator;/* make separator a string*/
475
0
  sep[1] = '\0';
476
0
        NCJnewstring(NCJ_STRING,sep,&jtmp);
477
0
        if((stat = NCJinsert(jvar,"dimension_separator",jtmp))<0) {stat = NC_EINVAL; goto done;}
478
0
        jtmp = NULL;
479
0
    }
480
481
0
    nullfree(key);
482
0
    key = NULL;
483
0
    NCZ_varkey(var, &key);
484
0
    if((stat=NCZMD_update_json_array(zinfo,key,(const NCjson*)jvar))) {
485
0
        goto done;
486
0
    }
487
488
    /* Capture dimref names as FQNs */
489
0
    if(var->ndims > 0) {
490
0
        if((dimrefs = nclistnew())==NULL) {stat = NC_ENOMEM; goto done;}
491
0
  for(i=0;i<var->ndims;i++) {
492
0
      NC_DIM_INFO_T* dim = var->dim[i];
493
0
      if((stat = NCZ_dimkey(dim,&dimpath))) goto done;
494
0
      nclistpush(dimrefs,dimpath);
495
0
      dimpath = NULL;
496
0
  }
497
0
    }
498
499
    /* Build the NCZ_V2_ARRAY object */
500
0
    {
501
  /* Create the dimrefs json object */
502
0
  NCJnew(NCJ_ARRAY,&jdimrefs);
503
0
  for(i=0;i<nclistlength(dimrefs);i++) {
504
0
      const char* dim = nclistget(dimrefs,i);
505
0
      NCJaddstring(jdimrefs,NCJ_STRING,dim);
506
0
  }
507
0
  NCJnew(NCJ_DICT,&jncvar);
508
509
  /* Insert dimension_referencess  */
510
0
  if((stat = NCJinsert(jncvar,"dimension_references",jdimrefs))<0) {stat = NC_EINVAL; goto done;}
511
0
  jdimrefs = NULL; /* Avoid memory problems */
512
513
  /* Add the _Storage flag */
514
  /* Record if this is a scalar */
515
0
  if(var->ndims == 0) {
516
0
      NCJnewstring(NCJ_INT,"1",&jtmp);
517
0
      if((stat = NCJinsert(jncvar,"scalar",jtmp))<0) {stat = NC_EINVAL; goto done;}
518
0
      jtmp = NULL;
519
0
  }
520
  /* everything looks like it is chunked */
521
0
  NCJnewstring(NCJ_STRING,"chunked",&jtmp);
522
0
  if((stat = NCJinsert(jncvar,"storage",jtmp))<0) {stat = NC_EINVAL; goto done;}
523
0
  jtmp = NULL;
524
0
    }
525
526
    /* Build .zattrs object */
527
0
    assert(var->att);
528
0
    NCJnew(NCJ_DICT,&jatts);
529
0
    NCJnew(NCJ_DICT,&jtypes);
530
0
    if((stat = ncz_sync_atts(file,(NC_OBJ*)var, var->att, jatts, jtypes, isclose))) goto done;
531
532
0
    if(!purezarr && jncvar != NULL) {
533
        /* Insert _nczarr_array */
534
0
        if((stat=insert_attr(jatts,jtypes,NCZ_V2_ARRAY,jncvar,"|J0"))) goto done;
535
0
  jncvar = NULL;
536
0
    }
537
538
    /* As a last mod to jatts, optionally insert the jtypes as an attribute and add _nczarr_attr as attribute*/
539
0
    if(!purezarr && jtypes != NULL) {
540
0
  if((stat = insert_nczarr_attr(jatts,jtypes))) goto done;
541
0
  jtypes = NULL;
542
0
    }
543
544
    /* Write out the .zattrs */
545
0
    nullfree(key);
546
0
    key = NULL;
547
0
    NCZ_varkey(var, &key);
548
0
    if((stat = NCZMD_update_json_attrs(zinfo, key, jatts))) goto done;
549
550
0
    var->created = 1;
551
552
0
done:
553
0
    nclistfreeall(dimrefs);
554
0
    nullfree(key);
555
0
    nullfree(dtypename);
556
0
    nullfree(dimpath);
557
0
    NCJreclaim(jvar);
558
0
    NCJreclaim(jncvar);
559
0
    NCJreclaim(jtmp);
560
0
    NCJreclaim(jfill);
561
0
    NCJreclaim(jatts);
562
0
    NCJreclaim(jtypes);
563
0
    return ZUNTRACE(THROW(stat));
564
0
}
565
566
/**
567
 * @internal Synchronize variable meta data and data from memory to map.
568
 *
569
 * @param file Pointer to file struct
570
 * @param var Pointer to var struct
571
 * @param isclose If this called as part of nc_close() as opposed to nc_enddef().
572
 *
573
 * @return ::NC_NOERR No error.
574
 * @author Dennis Heimbigner
575
 */
576
static int
577
ncz_sync_var(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int isclose)
578
0
{
579
0
    int stat = NC_NOERR;
580
0
    NCZ_VAR_INFO_T* zvar = var->format_var_info;
581
582
0
    ZTRACE(3,"file=%s var=%s isclose=%d",file->controller->path,var->hdr.name,isclose);
583
584
0
    if(isclose) {
585
0
  if((stat = ncz_sync_var_meta(file,var,isclose))) goto done;
586
0
    }
587
588
    /* flush only chunks that have been written */
589
0
    if(zvar->cache) {
590
0
        if((stat = NCZ_flush_chunk_cache(zvar->cache)))
591
0
      goto done;
592
0
    }
593
594
0
done:
595
0
    return ZUNTRACE(THROW(stat));
596
0
}
597
598
599
/*
600
Flush all chunks to disk. Create any that are missing
601
and fill as needed.
602
*/
603
int
604
ncz_write_var(NC_VAR_INFO_T* var)
605
0
{
606
0
    int stat = NC_NOERR;
607
0
    NCZ_VAR_INFO_T* zvar = (NCZ_VAR_INFO_T*)var->format_var_info;
608
609
0
    ZTRACE(3,"var=%s",var->hdr.name);
610
611
    /* Flush the cache */
612
0
    if(zvar->cache) {
613
0
        if((stat = NCZ_flush_chunk_cache(zvar->cache))) goto done;
614
0
    }
615
616
#ifdef FILLONCLOSE
617
    /* If fill is enabled, then create missing chunks */
618
    if(!var->no_fill) {
619
        int i;
620
    NCZOdometer* chunkodom =  NULL;
621
    NC_FILE_INFO_T* file = var->container->nc4_info;
622
    NCZ_FILE_INFO_T* zfile = (NCZ_FILE_INFO_T*)file->format_file_info;
623
    NCZMAP* map = zfile->map;
624
    size64_t start[NC_MAX_VAR_DIMS];
625
    size64_t stop[NC_MAX_VAR_DIMS];
626
    size64_t stride[NC_MAX_VAR_DIMS];
627
    char* key = NULL;
628
629
    if(var->ndims == 0) { /* scalar */
630
  start[i] = 0;
631
  stop[i] = 1;
632
        stride[i] = 1;
633
    } else {
634
        for(i=0;i<var->ndims;i++) {
635
      size64_t nchunks = ceildiv(var->dim[i]->len,var->chunksizes[i]);
636
      start[i] = 0;
637
      stop[i] = nchunks;
638
      stride[i] = 1;
639
        }
640
    }
641
642
    {
643
  if(zvar->scalar) {
644
      if((chunkodom = nczodom_new(1,start,stop,stride,stop))==NULL)
645
  } else {
646
      /* Iterate over all the chunks to create missing ones */
647
      if((chunkodom = nczodom_new(var->ndims,start,stop,stride,stop))==NULL)
648
          {stat = NC_ENOMEM; goto done;}
649
  }
650
  for(;nczodom_more(chunkodom);nczodom_next(chunkodom)) {
651
      size64_t* indices = nczodom_indices(chunkodom);
652
      /* Convert to key */
653
      if((stat = NCZ_buildchunkpath(zvar->cache,indices,&key))) goto done;
654
      switch (stat = nczmap_exists(map,key)) {
655
      case NC_NOERR: goto next; /* already exists */
656
      case NC_EEMPTY: break; /* does not exist, create it with fill */
657
      default: goto done; /* some other error */
658
      }
659
            /* If we reach here, then chunk does not exist, create it with fill */
660
      assert(zvar->cache->fillchunk != NULL);
661
      if((stat=nczmap_write(map,key,0,zvar->cache->chunksize,zvar->cache->fillchunk))) goto done;
662
next:
663
      nullfree(key);
664
      key = NULL;
665
  }
666
    }
667
    nczodom_free(chunkodom);
668
    nullfree(key);
669
    }
670
#endif /*FILLONCLOSE*/
671
672
0
done:
673
0
    return ZUNTRACE(THROW(stat));
674
0
}
675
676
/**
677
 * @internal Synchronize attribute data from memory to map.
678
 *
679
 * @param file
680
 * @param container Pointer to grp|var struct containing the attributes
681
 * @param attlist
682
 * @param jattsp
683
 * @param jtypesp
684
 *
685
 * @return ::NC_NOERR No error.
686
 * @author Dennis Heimbigner
687
 */
688
int
689
ncz_sync_atts(NC_FILE_INFO_T* file, NC_OBJ* container, NCindex* attlist, NCjson* jatts, NCjson* jtypes, int isclose)
690
0
{
691
0
    int stat = NC_NOERR;
692
0
    size_t i;
693
0
    NCZ_FILE_INFO_T* zinfo = NULL;
694
0
    NCjson* jdimrefs = NULL;
695
0
    NCjson* jdict = NULL;
696
0
    NCjson* jint = NULL;
697
0
    NCjson* jdata = NULL;
698
0
    char* key = NULL;
699
0
    char* content = NULL;
700
0
    char* dimpath = NULL;
701
0
    int isxarray = 0;
702
0
    int inrootgroup = 0;
703
0
    NC_VAR_INFO_T* var = NULL;
704
0
    NC_GRP_INFO_T* grp = NULL;
705
0
    char* tname = NULL;
706
0
    int purezarr = 0;
707
0
    int endianness = (NC_isLittleEndian()?NC_ENDIAN_LITTLE:NC_ENDIAN_BIG);
708
709
0
    NC_UNUSED(isclose);
710
    
711
0
    LOG((3, "%s", __func__));
712
0
    ZTRACE(3,"file=%s container=%s |attlist|=%u",file->controller->path,container->name,(unsigned)ncindexsize(attlist));
713
    
714
0
    if(container->sort == NCVAR) {
715
0
        var = (NC_VAR_INFO_T*)container;
716
0
  if(var->container && var->container->parent == NULL)
717
0
      inrootgroup = 1;
718
0
    } else if(container->sort == NCGRP) {
719
0
        grp = (NC_GRP_INFO_T*)container;
720
0
    }
721
    
722
0
    zinfo = file->format_file_info;
723
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
724
0
    if(zinfo->controls.flags & FLAG_XARRAYDIMS) isxarray = 1;
725
726
0
    if(ncindexsize(attlist) > 0) {
727
        /* Walk all the attributes convert to json and collect the dtype */
728
0
        for(i=0;i<ncindexsize(attlist);i++) {
729
0
      NC_ATT_INFO_T* a = (NC_ATT_INFO_T*)ncindexith(attlist,i);
730
0
      size_t typesize = 0;
731
0
      if(a->nc_typeid > NC_MAX_ATOMIC_TYPE)
732
0
          {stat = (THROW(NC_ENCZARR)); goto done;}
733
0
      if(a->nc_typeid == NC_STRING)
734
0
          typesize = (size_t)NCZ_get_maxstrlen(container);
735
0
      else
736
0
          {if((stat = NC4_inq_atomic_type(a->nc_typeid,NULL,&typesize))) goto done;}
737
      /* Convert to storable json */
738
0
      if((stat = NCZ_stringconvert(a->nc_typeid,a->len,a->data,&jdata))) goto done;
739
740
      /* Collect the corresponding dtype */
741
0
            if((stat = ncz_nctype2dtype(a->nc_typeid,endianness,purezarr,typesize,&tname))) goto done;
742
743
      /* Insert the attribute; consumes jdata */
744
0
      if((stat = insert_attr(jatts,jtypes,a->hdr.name, jdata, tname))) goto done;
745
746
      /* cleanup */
747
0
            nullfree(tname); tname = NULL;
748
0
      jdata = NULL;
749
750
0
        }
751
0
    }
752
    /* Construct container path */
753
0
    if(container->sort == NCGRP)
754
0
  stat = NCZ_grpkey(grp,&key);
755
0
    else
756
0
  stat = NCZ_varkey(var,&key);
757
0
    if(stat)
758
0
  goto done;
759
760
0
    if(container->sort == NCVAR) { 
761
0
        if(isxarray) {
762
      /* Optionally insert XARRAY-related attributes:
763
    - XARRAYSCALAR
764
    - _ARRAY_ATTRIBUTE
765
      */
766
0
      NCJnew(NCJ_ARRAY,&jdimrefs);
767
      /* Fake the scalar case */
768
0
      if(var->ndims == 0)
769
0
          NCJaddstring(jdimrefs,NCJ_STRING,XARRAYSCALAR);
770
      /* Walk the dimensions and capture the names */
771
0
      for(i=0;i<var->ndims;i++) {
772
0
    char* dimname;
773
0
          NC_DIM_INFO_T* dim = var->dim[i];
774
0
    dimname = strdup(dim->hdr.name);
775
0
    if(dimname == NULL) {stat = NC_ENOMEM; goto done;}
776
0
          NCJaddstring(jdimrefs,NCJ_STRING,dimname);
777
0
            nullfree(dimname); dimname = NULL;
778
0
      }
779
      /* Add the _ARRAY_DIMENSIONS attribute */
780
0
      if((stat = NCJinsert(jatts,NC_XARRAY_DIMS,jdimrefs))<0) {stat = NC_EINVAL; goto done;}
781
0
      jdimrefs = NULL;
782
0
        }
783
0
    }
784
    /* Add Quantize Attribute */
785
0
    if(container->sort == NCVAR && var && var->quantize_mode > 0) {    
786
0
  char mode[64];
787
0
  snprintf(mode,sizeof(mode),"%d",var->nsd);
788
0
        NCJnewstring(NCJ_INT,mode,&jint);
789
  /* Insert the quantize attribute */
790
0
  switch (var->quantize_mode) {
791
0
  case NC_QUANTIZE_BITGROOM:
792
0
      if((stat = NCJinsert(jatts,NC_QUANTIZE_BITGROOM_ATT_NAME,jint))<0) {stat = NC_EINVAL; goto done;} 
793
0
      jint = NULL;
794
0
      break;
795
0
  case NC_QUANTIZE_GRANULARBR:
796
0
      if((stat = NCJinsert(jatts,NC_QUANTIZE_GRANULARBR_ATT_NAME,jint))<0) {stat = NC_EINVAL; goto done;} 
797
0
      jint = NULL;
798
0
      break;
799
0
  case NC_QUANTIZE_BITROUND:
800
0
      if((stat = NCJinsert(jatts,NC_QUANTIZE_BITROUND_ATT_NAME,jint))<0) {stat = NC_EINVAL; goto done;} 
801
0
      jint = NULL;
802
0
      break;
803
0
  default: break;
804
0
  }
805
0
    }
806
807
0
done:
808
0
    nullfree(key);
809
0
    nullfree(content);
810
0
    nullfree(dimpath);
811
0
    nullfree(tname);
812
0
    NCJreclaim(jdimrefs);
813
0
    NCJreclaim(jdict);
814
0
    NCJreclaim(jint);
815
0
    NCJreclaim(jdata);
816
0
    return ZUNTRACE(THROW(stat));
817
0
}
818
819
820
/**************************************************/
821
822
/**
823
@internal Extract attributes from a group or var and return
824
the corresponding NCjson dict.
825
@param map - [in] the map object for storage
826
@param container - [in] the containing object
827
@param jattsp    - [out] the json for .zattrs || NULL if not found
828
@param jtypesp   - [out] the json attribute type dict || NULL
829
@param jnczgrp   - [out] the json for _nczarr_group || NULL
830
@param jnczarray - [out] the json for _nczarr_array || NULL
831
@return NC_NOERR
832
@return NC_EXXX
833
@author Dennis Heimbigner
834
*/
835
static int
836
download_jatts(NC_FILE_INFO_T* file, NC_OBJ* container, const NCjson** jattsp, const NCjson** jtypesp)
837
0
{
838
0
    int stat = NC_NOERR;
839
0
    const NCjson* jatts = NULL;
840
0
    const NCjson* jtypes = NULL;
841
0
    const NCjson* jnczattr = NULL;
842
0
    NC_GRP_INFO_T* grp = NULL;
843
0
    NC_VAR_INFO_T* var = NULL;
844
0
    NCZ_GRP_INFO_T* zgrp = NULL;
845
0
    NCZ_VAR_INFO_T* zvar = NULL;
846
0
    NCZ_FILE_INFO_T* zinfo = (NCZ_FILE_INFO_T*)file->format_file_info;
847
0
    int purezarr = 0;
848
0
    int zarrkey = 0;
849
850
0
    ZTRACE(3,"container=%s ",container->name);
851
852
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
853
0
    zarrkey = (zinfo->controls.flags & FLAG_NCZARR_KEY)?1:0;
854
855
0
    if(container->sort == NCGRP) {
856
0
  grp = (NC_GRP_INFO_T*)container;
857
0
  zgrp = (NCZ_GRP_INFO_T*)grp->format_grp_info; 
858
0
  jatts = zgrp->zgroup.atts;
859
0
    } else {
860
0
  var = (NC_VAR_INFO_T*)container;
861
0
  zvar = (NCZ_VAR_INFO_T*)var->format_var_info;
862
0
  jatts = zvar->zarray.atts;
863
0
    }
864
0
    assert(purezarr || zarrkey || jatts != NULL);
865
866
0
    if(jatts != NULL) {
867
  /* Get _nczarr_attr from .zattrs */
868
0
        if((stat = NCJdictget(jatts,NCZ_V2_ATTR,&jnczattr))<0) {stat = NC_EINVAL; goto done;}
869
0
  if(jnczattr != NULL) {
870
      /* jnczattr attribute should be a dict */
871
0
      if(NCJsort(jnczattr) != NCJ_DICT) {stat = (THROW(NC_ENCZARR)); goto done;}
872
      /* Extract "types"; may not exist if only hidden attributes are defined */
873
0
      if((stat = NCJdictget(jnczattr,"types",&jtypes))<0) {stat = NC_EINVAL; goto done;}
874
0
      if(jtypes != NULL) {
875
0
          if(NCJsort(jtypes) != NCJ_DICT) {stat = (THROW(NC_ENCZARR)); goto done;}
876
0
      }
877
0
  }
878
0
    }
879
0
    if(jattsp) {*jattsp = jatts; jatts = NULL;}
880
0
    if(jtypes) {*jtypesp = jtypes; jtypes = NULL;}
881
882
0
done:
883
0
    return ZUNTRACE(THROW(stat));
884
0
}
885
886
/* Convert a JSON singleton or array of strings to a single string */
887
static int
888
zcharify(const NCjson* src, NCbytes* buf)
889
0
{
890
0
    int stat = NC_NOERR;
891
0
    size_t i;
892
0
    struct NCJconst jstr;
893
894
0
    memset(&jstr,0,sizeof(jstr));
895
896
0
    if(NCJsort(src) != NCJ_ARRAY) { /* singleton */
897
0
        if((stat = NCJcvt(src, NCJ_STRING, &jstr))<0) {stat = NC_EINVAL; goto done;}
898
0
        ncbytescat(buf,jstr.sval);
899
0
    } else for(i=0;i<NCJarraylength(src);i++) {
900
0
  NCjson* value = NCJith(src,i);
901
0
  if((stat = NCJcvt(value, NCJ_STRING, &jstr))<0) {stat = NC_EINVAL; goto done;}
902
0
  ncbytescat(buf,jstr.sval);
903
0
        nullfree(jstr.sval);jstr.sval = NULL;
904
0
    }
905
0
done:
906
0
    nullfree(jstr.sval);
907
0
    return stat;
908
0
}
909
910
/* Convert a json value to actual data values of an attribute. */
911
static int
912
zconvert(const NCjson* src, nc_type typeid, size_t typelen, int* countp, NCbytes* dst)
913
0
{
914
0
    int stat = NC_NOERR;
915
0
    int i;
916
0
    int count = 0;
917
    
918
0
    ZTRACE(3,"src=%s typeid=%d typelen=%u",NCJtotext(src,0),typeid,typelen);
919
      
920
    /* 3 cases:
921
       (1) singleton atomic value
922
       (2) array of atomic values
923
       (3) other JSON expression
924
    */
925
0
    switch (NCJsort(src)) {
926
0
    case NCJ_INT: case NCJ_DOUBLE: case NCJ_BOOLEAN: /* case 1 */
927
0
  count = 1;
928
0
  if((stat = NCZ_convert1(src, typeid, dst)))
929
0
      goto done;
930
0
  break;
931
932
0
    case NCJ_ARRAY:
933
0
        if(typeid == NC_CHAR) {
934
0
      if((stat = zcharify(src,dst))) goto done;
935
0
      count = ncbyteslength(dst);
936
0
        } else {
937
0
      count = NCJarraylength(src);
938
0
      for(i=0;i<count;i++) {
939
0
          NCjson* value = NCJith(src,i);
940
0
                if((stat = NCZ_convert1(value, typeid, dst))) goto done;
941
0
      }
942
0
  }
943
0
  break;
944
0
    case NCJ_STRING:
945
0
  if(typeid == NC_CHAR) {
946
0
      if((stat = zcharify(src,dst))) goto done;
947
0
      count = ncbyteslength(dst);
948
      /* Special case for "" */
949
0
      if(count == 0) {
950
0
          ncbytesappend(dst,'\0');
951
0
          count = 1;
952
0
      }
953
0
  } else {
954
0
      if((stat = NCZ_convert1(src, typeid, dst))) goto done;
955
0
      count = 1;
956
0
  }
957
0
  break;
958
0
    default: stat = (THROW(NC_ENCZARR)); goto done;
959
0
    }
960
0
    if(countp) *countp = count;
961
962
0
done:
963
0
    return ZUNTRACE(THROW(stat));
964
0
}
965
966
/*
967
Extract type and data for an attribute
968
*/
969
static int
970
computeattrinfo(const char* name, const NCjson* jtypes, nc_type typehint, int purezarr, NCjson* values,
971
    nc_type* typeidp, size_t* typelenp, size_t* lenp, void** datap)
972
0
{
973
0
    int stat = NC_NOERR;
974
0
    size_t i;
975
0
    size_t len, typelen;
976
0
    void* data = NULL;
977
0
    nc_type typeid;
978
979
0
    ZTRACE(3,"name=%s typehint=%d purezarr=%d values=|%s|",name,typehint,purezarr,NCJtotext(values,0));
980
981
    /* Get type info for the given att */
982
0
    typeid = NC_NAT;
983
0
    for(i=0;i<NCJdictlength(jtypes);i++) {
984
0
  NCjson* akey = NCJdictkey(jtypes,i);
985
0
  if(strcmp(NCJstring(akey),name)==0) {
986
0
      const NCjson* avalue = NULL;
987
0
      NCJdictget(jtypes,NCJstring(akey),&avalue);
988
0
      if((stat = ncz_dtype2nctype(NCJstring(avalue),typehint,purezarr,&typeid,NULL,NULL))) goto done;
989
//    if((stat = ncz_nctypedecode(atype,&typeid))) goto done;
990
0
      break;
991
0
  }
992
0
    }
993
0
    if(typeid > NC_MAX_ATOMIC_TYPE)
994
0
  {stat = NC_EINTERNAL; goto done;}
995
    /* Use the hint if given one */
996
0
    if(typeid == NC_NAT)
997
0
        typeid = typehint;
998
999
0
    if((stat = computeattrdata(typehint, &typeid, values, &typelen, &len, &data))) goto done;
1000
1001
0
    if(typeidp) *typeidp = typeid;
1002
0
    if(lenp) *lenp = len;
1003
0
    if(typelenp) *typelenp = typelen;
1004
0
    if(datap) {*datap = data; data = NULL;}
1005
1006
0
done:
1007
0
    nullfree(data);
1008
0
    return ZUNTRACEX(THROW(stat),"typeid=%d typelen=%d len=%u",*typeidp,*typelenp,*lenp);
1009
0
}
1010
1011
/*
1012
Extract data for an attribute
1013
*/
1014
static int
1015
computeattrdata(nc_type typehint, nc_type* typeidp, const NCjson* values, size_t* typelenp, size_t* countp, void** datap)
1016
0
{
1017
0
    int stat = NC_NOERR;
1018
0
    NCbytes* buf = ncbytesnew();
1019
0
    size_t typelen;
1020
0
    nc_type typeid = NC_NAT;
1021
0
    NCjson* jtext = NULL;
1022
0
    int reclaimvalues = 0;
1023
0
    int isjson = 0; /* 1 => attribute value is neither scalar nor array of scalars */
1024
0
    int count = 0; /* no. of attribute values */
1025
1026
0
    ZTRACE(3,"typehint=%d typeid=%d values=|%s|",typehint,*typeidp,NCJtotext(values,0));
1027
1028
    /* Get assumed type */
1029
0
    if(typeidp) typeid = *typeidp;
1030
0
    if(typeid == NC_NAT && !isjson) {
1031
0
        if((stat = NCZ_inferattrtype(values,typehint, &typeid))) goto done;
1032
0
    }
1033
1034
    /* See if this is a simple vector (or scalar) of atomic types */
1035
0
    isjson = NCZ_iscomplexjson(values,typeid);
1036
1037
0
    if(isjson) {
1038
  /* Apply the JSON attribute convention and convert to JSON string */
1039
0
  typeid = NC_CHAR;
1040
0
  if((stat = json_convention_read(values,&jtext))) goto done;
1041
0
  values = jtext; jtext = NULL;
1042
0
  reclaimvalues = 1;
1043
0
    } 
1044
1045
0
    if((stat = NC4_inq_atomic_type(typeid, NULL, &typelen)))
1046
0
        goto done;
1047
1048
    /* Convert the JSON attribute values to the actual netcdf attribute bytes */
1049
0
    if((stat = zconvert(values,typeid,typelen,&count,buf))) goto done;
1050
1051
0
    if(typelenp) *typelenp = typelen;
1052
0
    if(typeidp) *typeidp = typeid; /* return possibly inferred type */
1053
0
    if(countp) *countp = (size_t)count;
1054
0
    if(datap) *datap = ncbytesextract(buf);
1055
1056
0
done:
1057
0
    ncbytesfree(buf);
1058
0
    if(reclaimvalues) NCJreclaim((NCjson*)values); /* we created it */
1059
0
    return ZUNTRACEX(THROW(stat),"typelen=%d count=%u",(typelenp?*typelenp:0),(countp?*countp:-1));
1060
0
}
1061
1062
/**
1063
 * @internal Read file data from map to memory.
1064
 *
1065
 * @param file Pointer to file info struct.
1066
 *
1067
 * @return ::NC_NOERR No error.
1068
 * @author Dennis Heimbigner
1069
 */
1070
int
1071
ncz_read_file(NC_FILE_INFO_T* file)
1072
0
{
1073
0
    int stat = NC_NOERR;
1074
0
    NCjson* json = NULL;
1075
1076
0
    LOG((3, "%s: file: %s", __func__, file->controller->path));
1077
0
    ZTRACE(3,"file=%s",file->controller->path);
1078
    
1079
    /* _nczarr should already have been read in ncz_open_dataset */
1080
1081
    /* Now load the groups starting with root */
1082
0
    if((stat = define_grp(file,file->root_grp)))
1083
0
  goto done;
1084
1085
0
done:
1086
0
    NCJreclaim(json);
1087
0
    return ZUNTRACE(stat);
1088
0
}
1089
1090
/**
1091
 * @internal Read group data from map to memory
1092
 *
1093
 * @param file Pointer to file struct
1094
 * @param grp Pointer to grp struct
1095
 *
1096
 * @return ::NC_NOERR No error.
1097
 * @author Dennis Heimbigner
1098
 */
1099
static int
1100
define_grp(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp)
1101
0
{
1102
0
    int stat = NC_NOERR;
1103
0
    NCZ_FILE_INFO_T* zinfo = NULL;
1104
0
    NCZ_GRP_INFO_T* zgrp = NULL;
1105
0
    char* key = NULL;
1106
0
    NCjson* json = NULL;
1107
0
    const NCjson* jgroup = NULL;
1108
0
    const NCjson* jattrs = NULL;
1109
0
    const NCjson* jnczgrp = NULL;
1110
0
    NClist* dimdefs = nclistnew();
1111
0
    NClist* varnames = nclistnew();
1112
0
    NClist* subgrps = nclistnew();
1113
0
    int purezarr = 0;
1114
1115
0
    LOG((3, "%s: dims: %s", __func__, key));
1116
0
    ZTRACE(3,"file=%s grp=%s",file->controller->path,grp->hdr.name);
1117
    
1118
0
    zinfo = file->format_file_info;
1119
0
    zgrp = grp->format_grp_info;
1120
1121
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
1122
1123
    /* Construct grp path */
1124
0
    if((stat = NCZ_grpkey(grp,&key))) goto done;
1125
1126
    /* Download .zgroup and .zattrs */
1127
0
    nullfree(zgrp->zgroup.prefix);
1128
0
    zgrp->zgroup.prefix = strdup(key);
1129
0
    NCJreclaim(zgrp->zgroup.obj);
1130
0
    NCJreclaim(zgrp->zgroup.atts);
1131
0
    if ((stat = NCZMD_fetch_json_group(zinfo, key, &zgrp->zgroup.obj)) \
1132
0
    || (stat = NCZMD_fetch_json_attrs(zinfo, key, &zgrp->zgroup.atts))) {
1133
0
        goto done;
1134
0
    }
1135
0
    jgroup = zgrp->zgroup.obj;
1136
0
    jattrs = zgrp->zgroup.atts;
1137
1138
0
    if(purezarr) {
1139
0
  if((stat = parse_group_content_pure(zinfo,grp,varnames,subgrps)))
1140
0
      goto done;
1141
0
        purezarr = 1;
1142
0
    } else { /*!purezarr*/
1143
0
  if(jgroup == NULL) { /* does not exist, use search */
1144
0
            if((stat = parse_group_content_pure(zinfo,grp,varnames,subgrps))) goto done;
1145
0
      purezarr = 1;
1146
0
  }
1147
0
  if(jattrs == NULL)  { /* does not exist, use search */
1148
0
            if((stat = parse_group_content_pure(zinfo,grp,varnames,subgrps))) goto done;
1149
0
      purezarr = 1;
1150
0
  } else { /* Extract the NCZ_V2_GROUP attribute*/
1151
0
            if((stat = getnczarrkey((NC_OBJ*)grp,NCZ_V2_GROUP,&jnczgrp))) goto done;
1152
0
  }
1153
0
  nullfree(key); key = NULL;
1154
0
  if(jnczgrp) {
1155
            /* Pull out lists about group content */
1156
0
      if((stat = parse_group_content(jnczgrp,dimdefs,varnames,subgrps)))
1157
0
          goto done;
1158
0
  }
1159
0
    }
1160
1161
0
    if(!purezarr) {
1162
  /* Define dimensions */
1163
0
  if((stat = define_dims(file,grp,dimdefs))) goto done;
1164
0
    }
1165
1166
    /* Define vars taking xarray into account */
1167
0
    if((stat = define_vars(file,grp,varnames))) goto done;
1168
1169
    /* Define sub-groups */
1170
0
    if((stat = define_subgrps(file,grp,subgrps))) goto done;
1171
1172
0
done:
1173
0
    NCJreclaim(json);
1174
0
    nclistfreeall(dimdefs);
1175
0
    nclistfreeall(varnames);
1176
0
    nclistfreeall(subgrps);
1177
0
    nullfree(key);
1178
0
    return ZUNTRACE(stat);
1179
0
}
1180
1181
1182
/**
1183
@internal Read attributes from a group or var and create a list
1184
of annotated NC_ATT_INFO_T* objects. This will process
1185
_NCProperties attribute specially.
1186
@param zfile - [in] the containing file (annotation)
1187
@param container - [in] the containing object
1188
@return NC_NOERR
1189
@author Dennis Heimbigner
1190
*/
1191
int
1192
ncz_read_atts(NC_FILE_INFO_T* file, NC_OBJ* container)
1193
0
{
1194
0
    int stat = NC_NOERR;
1195
0
    size_t i;
1196
0
    char* fullpath = NULL;
1197
0
    char* key = NULL;
1198
0
    NCZ_FILE_INFO_T* zinfo = NULL;
1199
0
    NC_VAR_INFO_T* var = NULL;
1200
0
    NCZ_VAR_INFO_T* zvar = NULL;
1201
0
    NC_GRP_INFO_T* grp = NULL;
1202
0
    NCZ_GRP_INFO_T* zgrp = NULL;
1203
0
    NC_ATT_INFO_T* att = NULL;
1204
0
    NCindex* attlist = NULL;
1205
0
    nc_type typeid;
1206
0
    size_t len, typelen;
1207
0
    void* data = NULL;
1208
0
    NC_ATT_INFO_T* fillvalueatt = NULL;
1209
0
    nc_type typehint = NC_NAT;
1210
0
    int purezarr,zarrkeys;
1211
0
    const NCjson* jattrs = NULL;
1212
0
    const NCjson* jtypes = NULL;
1213
0
    struct ZARROBJ* zobj = NULL;
1214
1215
0
    ZTRACE(3,"file=%s container=%s",file->controller->path,container->name);
1216
1217
0
    zinfo = file->format_file_info;
1218
0
    purezarr = (zinfo->controls.flags & FLAG_PUREZARR)?1:0;
1219
0
    zarrkeys = (zinfo->controls.flags & FLAG_NCZARR_KEY)?1:0;
1220
 
1221
0
    if(container->sort == NCGRP) { 
1222
0
  grp = ((NC_GRP_INFO_T*)container);
1223
0
  attlist =  grp->att;
1224
0
        zgrp = (NCZ_GRP_INFO_T*)(grp->format_grp_info);
1225
0
  zobj = &zgrp->zgroup;
1226
0
    } else {
1227
0
  var = ((NC_VAR_INFO_T*)container);
1228
0
  attlist =  var->att;
1229
0
        zvar = (NCZ_VAR_INFO_T*)(var->format_var_info);
1230
0
  zobj = &zvar->zarray;
1231
0
    }
1232
0
    assert(purezarr || zarrkeys || zobj->obj != NULL);
1233
1234
0
    if((stat = download_jatts(file, container, &jattrs, &jtypes))) goto done;
1235
1236
0
    if(jattrs != NULL) {
1237
  /* Iterate over the attributes to create the in-memory attributes */
1238
  /* Watch for special cases: _FillValue and  _ARRAY_DIMENSIONS (xarray), etc. */
1239
0
  for(i=0;i<NCJdictlength(jattrs);i++) {
1240
0
      NCjson* key = NCJdictkey(jattrs,i);
1241
0
      NCjson* value = NCJdictvalue(jattrs,i);
1242
0
      const NC_reservedatt* ra = NULL;
1243
0
      int isfillvalue = 0;
1244
0
          int isdfaltmaxstrlen = 0;
1245
0
            int ismaxstrlen = 0;
1246
0
      const char* aname = NCJstring(key);
1247
      /* See if this is a notable attribute */
1248
0
      if(var != NULL && strcmp(aname,NC_ATT_FILLVALUE)==0) isfillvalue = 1;
1249
0
      if(grp != NULL && grp->parent == NULL && strcmp(aname,NC_NCZARR_DEFAULT_MAXSTRLEN_ATTR)==0)
1250
0
          isdfaltmaxstrlen = 1;
1251
0
      if(var != NULL && strcmp(aname,NC_NCZARR_MAXSTRLEN_ATTR)==0)
1252
0
          ismaxstrlen = 1;
1253
1254
      /* See if this is reserved attribute */
1255
0
      ra = NC_findreserved(aname);
1256
0
      if(ra != NULL) {
1257
    /* case 1: name = _NCProperties, grp=root, varid==NC_GLOBAL */
1258
0
    if(strcmp(aname,NCPROPS)==0 && grp != NULL && file->root_grp == grp) {
1259
        /* Setup provenance */
1260
0
        if(NCJsort(value) != NCJ_STRING)
1261
0
      {stat = (THROW(NC_ENCZARR)); goto done;} /*malformed*/
1262
0
        if((stat = NCZ_read_provenance(file,aname,NCJstring(value))))
1263
0
      goto done;
1264
0
    }
1265
    /* case 2: name = _ARRAY_DIMENSIONS, sort==NCVAR, flags & HIDDENATTRFLAG */
1266
0
    if(strcmp(aname,NC_XARRAY_DIMS)==0 && var != NULL && (ra->flags & HIDDENATTRFLAG)) {
1267
                /* store for later */
1268
0
        size_t i;
1269
0
        assert(NCJsort(value) == NCJ_ARRAY);
1270
0
        if((zvar->xarray = nclistnew())==NULL)
1271
0
            {stat = NC_ENOMEM; goto done;}
1272
0
        for(i=0;i<NCJarraylength(value);i++) {
1273
0
      const NCjson* k = NCJith(value,i);
1274
0
      assert(k != NULL && NCJsort(k) == NCJ_STRING);
1275
0
      nclistpush(zvar->xarray,strdup(NCJstring(k)));
1276
0
        }
1277
0
    }
1278
    /* case other: if attribute is hidden */
1279
0
    if(ra->flags & HIDDENATTRFLAG) continue; /* ignore it */
1280
0
      }
1281
0
      typehint = NC_NAT;
1282
0
      if(isfillvalue)
1283
0
          typehint = var->type_info->hdr.id ; /* if unknown use the var's type for _FillValue */
1284
      /* Create the attribute */
1285
      /* Collect the attribute's type and value  */
1286
0
      if((stat = computeattrinfo(aname,jtypes,typehint,purezarr,value,
1287
0
           &typeid,&typelen,&len,&data)))
1288
0
    goto done;
1289
0
      if((stat = ncz_makeattr(container,attlist,aname,typeid,len,data,&att)))
1290
0
    goto done;
1291
      /* No longer need this copy of the data */
1292
0
        if((stat = NC_reclaim_data_all(file->controller,att->nc_typeid,data,len))) goto done;           
1293
0
      data = NULL;
1294
0
      if(isfillvalue)
1295
0
          fillvalueatt = att;
1296
0
      if(ismaxstrlen && att->nc_typeid == NC_INT)
1297
0
          zvar->maxstrlen = ((int*)att->data)[0];
1298
0
      if(isdfaltmaxstrlen && att->nc_typeid == NC_INT)
1299
0
          zinfo->default_maxstrlen = ((int*)att->data)[0];
1300
0
  }
1301
0
    }
1302
    /* If we have not read a _FillValue, then go ahead and create it */
1303
0
    if(fillvalueatt == NULL && container->sort == NCVAR) {
1304
0
  if((stat = ncz_create_fillvalue((NC_VAR_INFO_T*)container)))
1305
0
      goto done;
1306
0
    }
1307
1308
    /* Remember that we have read the atts for this var or group. */
1309
0
    if(container->sort == NCVAR)
1310
0
  ((NC_VAR_INFO_T*)container)->atts_read = 1;
1311
0
    else
1312
0
  ((NC_GRP_INFO_T*)container)->atts_read = 1;
1313
1314
0
done:
1315
0
    if(data != NULL)
1316
0
        stat = NC_reclaim_data(file->controller,att->nc_typeid,data,len);
1317
0
    nullfree(fullpath);
1318
0
    nullfree(key);
1319
0
    return ZUNTRACE(THROW(stat));
1320
0
}
1321
1322
/**
1323
 * @internal Materialize dimensions into memory
1324
 *
1325
 * @param file Pointer to file info struct.
1326
 * @param grp Pointer to grp info struct.
1327
 * @param diminfo List of (name,length,isunlimited) triples
1328
 *
1329
 * @return ::NC_NOERR No error.
1330
 * @author Dennis Heimbigner
1331
 */
1332
static int
1333
define_dims(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* diminfo)
1334
0
{
1335
0
    size_t i;
1336
0
    int stat = NC_NOERR;
1337
1338
0
    ZTRACE(3,"file=%s grp=%s |diminfo|=%u",file->controller->path,grp->hdr.name,nclistlength(diminfo));
1339
1340
    /* Reify each dim in turn */
1341
0
    for(i = 0; i < nclistlength(diminfo); i+=3) {
1342
0
  NC_DIM_INFO_T* dim = NULL;
1343
0
  size64_t len = 0;
1344
0
  long long isunlim = 0;
1345
0
  const char* name = nclistget(diminfo,i);
1346
0
  const char* slen = nclistget(diminfo,i+1);
1347
0
  const char* sisunlimited = nclistget(diminfo,i+2);
1348
1349
  /* Create the NC_DIM_INFO_T object */
1350
0
  sscanf(slen,"%lld",&len); /* Get length */
1351
0
  if(sisunlimited != NULL)
1352
0
      sscanf(sisunlimited,"%lld",&isunlim); /* Get unlimited flag */
1353
0
  else
1354
0
      isunlim = 0;
1355
0
  if((stat = nc4_dim_list_add(grp, name, (size_t)len, -1, &dim)))
1356
0
      goto done;
1357
0
  dim->unlimited = (isunlim ? 1 : 0);
1358
0
  if((dim->format_dim_info = calloc(1,sizeof(NCZ_DIM_INFO_T))) == NULL)
1359
0
      {stat = NC_ENOMEM; goto done;}
1360
0
  ((NCZ_DIM_INFO_T*)dim->format_dim_info)->common.file = file;
1361
0
    }
1362
1363
0
done:
1364
0
    return ZUNTRACE(THROW(stat));
1365
0
}
1366
1367
1368
/**
1369
 * @internal Materialize single var into memory;
1370
 * Take xarray and purezarr into account.
1371
 *
1372
 * @param file Pointer to file info struct.
1373
 * @param grp Pointer to grp info struct.
1374
 * @param varname name of variable in this group
1375
 *
1376
 * @return ::NC_NOERR No error.
1377
 * @author Dennis Heimbigner
1378
 */
1379
static int
1380
define_var1(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, const char* varname)
1381
0
{
1382
0
    int stat = NC_NOERR;
1383
0
    size_t j;
1384
0
    NCZ_FILE_INFO_T* zinfo = NULL;
1385
0
    int purezarr = 0;
1386
0
    int xarray = 0;
1387
    /* per-variable info */
1388
0
    NC_VAR_INFO_T* var = NULL;
1389
0
    NCZ_VAR_INFO_T* zvar = NULL;
1390
0
    const NCjson* jvar = NULL;
1391
0
    const NCjson* jatts = NULL; /* corresponding to jvar */
1392
0
    const NCjson* jncvar = NULL;
1393
0
    const NCjson* jdimrefs = NULL;
1394
0
    const NCjson* jvalue = NULL;
1395
0
    char* key = NULL;
1396
0
    size64_t* shapes = NULL;
1397
0
    NClist* dimnames = NULL;
1398
0
    int varsized = 0;
1399
0
    int suppress = 0; /* Abort processing of this variable */
1400
0
    nc_type vtype = NC_NAT;
1401
0
    int vtypelen = 0;
1402
0
    size_t rank = 0;
1403
0
    size_t zarr_rank = 0; /* Need to watch out for scalars */
1404
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
1405
    const NCjson* jfilter = NULL;
1406
    int chainindex = 0;
1407
#endif
1408
1409
0
    ZTRACE(3,"file=%s grp=%s varname=%s",file->controller->path,grp->hdr.name,varname);
1410
1411
0
    zinfo = file->format_file_info;
1412
1413
0
    if(zinfo->controls.flags & FLAG_PUREZARR) purezarr = 1;
1414
0
    if(zinfo->controls.flags & FLAG_XARRAYDIMS) {xarray = 1;}
1415
1416
0
    dimnames = nclistnew();
1417
1418
0
    if((stat = nc4_var_list_add2(grp, varname, &var)))
1419
0
  goto done;
1420
1421
    /* And its annotation */
1422
0
    if((zvar = calloc(1,sizeof(NCZ_VAR_INFO_T)))==NULL)
1423
0
  {stat = NC_ENOMEM; goto done;}
1424
0
    var->format_var_info = zvar;
1425
0
    zvar->common.file = file;
1426
1427
    /* pretend it was created */
1428
0
    var->created = 1;
1429
1430
    /* Indicate we do not have quantizer yet */
1431
0
    var->quantize_mode = -1;
1432
1433
    /* Construct var path */
1434
0
    if((stat = NCZ_varkey(var,&key)))
1435
0
  goto done;
1436
1437
0
    if ((stat = NCZMD_fetch_json_array(zinfo, key, &zvar->zarray.obj)) \
1438
0
    || (stat = NCZMD_fetch_json_attrs(zinfo, key, &zvar->zarray.atts))) {
1439
0
        goto done;
1440
0
    }
1441
0
    jvar = zvar->zarray.obj;
1442
0
    jatts = zvar->zarray.atts;
1443
0
    assert(jvar == NULL || NCJsort(jvar) == NCJ_DICT);
1444
0
    assert(jatts == NULL || NCJsort(jatts) == NCJ_DICT);
1445
1446
    /* Verify the format */
1447
0
    {
1448
0
  int version;
1449
0
  if((stat = NCJdictget(jvar,"zarr_format",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1450
0
  sscanf(NCJstring(jvalue),"%d",&version);
1451
0
  if(version != zinfo->format.zarr)
1452
0
      {stat = (THROW(NC_ENCZARR)); goto done;}
1453
0
    }
1454
1455
    /* Set the type and endianness of the variable */
1456
0
    {
1457
0
  int endianness;
1458
0
  if((stat = NCJdictget(jvar,"dtype",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1459
  /* Convert dtype to nc_type + endianness */
1460
0
  if((stat = ncz_dtype2nctype(NCJstring(jvalue),NC_NAT,purezarr,&vtype,&endianness,&vtypelen)))
1461
0
      goto done;
1462
0
  if(vtype > NC_NAT && vtype <= NC_MAX_ATOMIC_TYPE) {
1463
      /* Locate the NC_TYPE_INFO_T object */
1464
0
      if((stat = ncz_gettype(file,grp,vtype,&var->type_info)))
1465
0
    goto done;
1466
0
  } else {stat = NC_EBADTYPE; goto done;}
1467
#if 0 /* leave native in place */
1468
  if(endianness == NC_ENDIAN_NATIVE)
1469
      endianness = zinfo->native_endianness;
1470
  if(endianness == NC_ENDIAN_NATIVE)
1471
      endianness = (NC_isLittleEndian()?NC_ENDIAN_LITTLE:NC_ENDIAN_BIG);
1472
  if(endianness == NC_ENDIAN_LITTLE || endianness == NC_ENDIAN_BIG) {
1473
      var->endianness = endianness;
1474
  } else {stat = NC_EBADTYPE; goto done;}
1475
#else
1476
0
  var->endianness = endianness;
1477
0
#endif
1478
0
  var->type_info->endianness = var->endianness; /* Propagate */
1479
0
  if(vtype == NC_STRING) {
1480
0
      zvar->maxstrlen = vtypelen;
1481
0
      vtypelen = sizeof(char*); /* in-memory len */
1482
0
      if(zvar->maxstrlen <= 0) zvar->maxstrlen = NCZ_get_maxstrlen((NC_OBJ*)var);
1483
0
  }
1484
0
    }
1485
1486
0
    if(!purezarr) {
1487
0
  if(jatts == NULL) {stat = NC_ENCZARR; goto done;}
1488
  /* Extract the _NCZARR_ARRAY values */
1489
  /* Do this first so we know about storage esp. scalar */
1490
  /* Extract the NCZ_V2_ARRAY dict */
1491
0
  if((stat = getnczarrkey((NC_OBJ*)var,NCZ_V2_ARRAY,&jncvar))) goto done;
1492
0
  if(jncvar == NULL) {stat = NC_ENCZARR; goto done;}
1493
0
  assert((NCJsort(jncvar) == NCJ_DICT));
1494
  /* Extract scalar flag */
1495
0
  if((stat = NCJdictget(jncvar,"scalar",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1496
0
  if(jvalue != NULL) {
1497
0
      var->storage = NC_CHUNKED;
1498
0
      zvar->scalar = 1;
1499
0
  }
1500
  /* Extract storage flag */
1501
0
  if((stat = NCJdictget(jncvar,"storage",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1502
0
  if(jvalue != NULL)
1503
0
      var->storage = NC_CHUNKED;
1504
  /* Extract dimrefs list  */
1505
0
  if((stat = dictgetalt(jncvar,"dimension_references","dimrefs",&jdimrefs))) goto done;
1506
0
  if(jdimrefs != NULL) { /* Extract the dimref names */
1507
0
      assert((NCJsort(jdimrefs) == NCJ_ARRAY));
1508
0
      if(zvar->scalar) {
1509
0
    assert(NCJarraylength(jdimrefs) == 0);         
1510
0
      } else {
1511
0
    rank = NCJarraylength(jdimrefs);
1512
0
    for(j=0;j<rank;j++) {
1513
0
        const NCjson* dimpath = NCJith(jdimrefs,j);
1514
0
        assert(NCJsort(dimpath) == NCJ_STRING);
1515
0
        nclistpush(dimnames,strdup(NCJstring(dimpath)));
1516
0
    }
1517
0
      }
1518
0
      jdimrefs = NULL; /* avoid double free */
1519
0
  } /* else  simulate it from the shape of the variable */
1520
0
    }
1521
1522
    /* Capture dimension_separator (must precede chunk cache creation) */
1523
0
    {
1524
0
  NCglobalstate* ngs = NC_getglobalstate();
1525
0
  assert(ngs != NULL);
1526
0
  zvar->dimension_separator = 0;
1527
0
  if((stat = NCJdictget(jvar,"dimension_separator",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1528
0
  if(jvalue != NULL) {
1529
      /* Verify its value */
1530
0
      if(NCJsort(jvalue) == NCJ_STRING && NCJstring(jvalue) != NULL && strlen(NCJstring(jvalue)) == 1)
1531
0
         zvar->dimension_separator = NCJstring(jvalue)[0];
1532
0
  }
1533
  /* If value is invalid, then use global default */
1534
0
  if(!islegaldimsep(zvar->dimension_separator))
1535
0
      zvar->dimension_separator = ngs->zarr.dimension_separator; /* use global value */
1536
0
  assert(islegaldimsep(zvar->dimension_separator)); /* we are hosed */
1537
0
    }
1538
1539
    /* fill_value; must precede calls to adjust cache */
1540
0
    {
1541
0
  if((stat = NCJdictget(jvar,"fill_value",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1542
0
  if(jvalue == NULL || NCJsort(jvalue) == NCJ_NULL)
1543
0
      var->no_fill = 1;
1544
0
  else {
1545
0
      size_t fvlen;
1546
0
      nc_type atypeid = vtype;
1547
0
      var->no_fill = 0;
1548
0
      if((stat = computeattrdata(var->type_info->hdr.id, &atypeid, jvalue, NULL, &fvlen, &var->fill_value)))
1549
0
    goto done;
1550
0
      assert(atypeid == vtype);
1551
      /* Note that we do not create the _FillValue
1552
         attribute here to avoid having to read all
1553
         the attributes and thus foiling lazy read.*/
1554
0
  }
1555
0
    }
1556
1557
    /* shape */
1558
0
    {
1559
0
  if((stat = NCJdictget(jvar,"shape",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1560
0
  if(NCJsort(jvalue) != NCJ_ARRAY) {stat = (THROW(NC_ENCZARR)); goto done;}
1561
  
1562
  /* Process the rank */
1563
0
  zarr_rank = NCJarraylength(jvalue);
1564
0
  if(zarr_rank == 0) {
1565
      /* suppress variable */
1566
0
      ZLOG(NCLOGWARN,"Empty shape for variable %s suppressed",var->hdr.name);
1567
0
      suppress = 1;
1568
0
      goto suppressvar;
1569
0
  }
1570
1571
0
  if(zvar->scalar) {
1572
0
      rank = 0;
1573
0
      zarr_rank = 1; /* Zarr does not support scalars */
1574
0
  } else 
1575
0
      rank = (zarr_rank = NCJarraylength(jvalue));
1576
1577
0
  if(zarr_rank > 0) {
1578
      /* Save the rank of the variable */
1579
0
      if((stat = nc4_var_set_ndims(var, rank))) goto done;
1580
      /* extract the shapes */
1581
0
      if((shapes = (size64_t*)malloc(sizeof(size64_t)*(size_t)zarr_rank)) == NULL)
1582
0
    {stat = (THROW(NC_ENOMEM)); goto done;}
1583
0
      if((stat = decodeints(jvalue, shapes))) goto done;
1584
0
  }
1585
0
    }
1586
1587
    /* chunks */
1588
0
    {
1589
0
  size64_t chunks[NC_MAX_VAR_DIMS];
1590
0
  if((stat = NCJdictget(jvar,"chunks",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1591
0
  if(jvalue != NULL && NCJsort(jvalue) != NCJ_ARRAY)
1592
0
      {stat = (THROW(NC_ENCZARR)); goto done;}
1593
  /* Verify the rank */
1594
0
  if(zvar->scalar || zarr_rank == 0) {
1595
0
      if(var->ndims != 0)
1596
0
    {stat = (THROW(NC_ENCZARR)); goto done;}
1597
0
      zvar->chunkproduct = 1;
1598
0
      zvar->chunksize = zvar->chunkproduct * var->type_info->size;
1599
      /* Create the cache */
1600
0
      if((stat = NCZ_create_chunk_cache(var,var->type_info->size*zvar->chunkproduct,zvar->dimension_separator,&zvar->cache)))
1601
0
    goto done;
1602
0
  } else {/* !zvar->scalar */
1603
0
      if(zarr_rank == 0) {stat = NC_ENCZARR; goto done;}
1604
0
      var->storage = NC_CHUNKED;
1605
0
      if(var->ndims != rank)
1606
0
    {stat = (THROW(NC_ENCZARR)); goto done;}
1607
0
      if((var->chunksizes = malloc(sizeof(size_t)*(size_t)zarr_rank)) == NULL)
1608
0
    {stat = NC_ENOMEM; goto done;}
1609
0
      if((stat = decodeints(jvalue, chunks))) goto done;
1610
      /* validate the chunk sizes */
1611
0
      zvar->chunkproduct = 1;
1612
0
      for(j=0;j<rank;j++) {
1613
0
    if(chunks[j] == 0)
1614
0
        {stat = (THROW(NC_ENCZARR)); goto done;}
1615
0
    var->chunksizes[j] = (size_t)chunks[j];
1616
0
    zvar->chunkproduct *= chunks[j];
1617
0
      }
1618
0
      zvar->chunksize = zvar->chunkproduct * var->type_info->size;
1619
      /* Create the cache */
1620
0
      if((stat = NCZ_create_chunk_cache(var,var->type_info->size*zvar->chunkproduct,zvar->dimension_separator,&zvar->cache)))
1621
0
    goto done;
1622
0
  }
1623
0
  if((stat = NCZ_adjust_var_cache(var))) goto done;
1624
0
    }
1625
    /* Capture row vs column major; currently, column major not used*/
1626
0
    {
1627
0
  if((stat = NCJdictget(jvar,"order",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1628
0
  if(strcmp(NCJstring(jvalue),"C") > 0)
1629
0
      ((NCZ_VAR_INFO_T*)var->format_var_info)->order = 1;
1630
0
  else ((NCZ_VAR_INFO_T*)var->format_var_info)->order = 0;
1631
0
    }
1632
    /* filters key */
1633
    /* From V2 Spec: A list of JSON objects providing codec configurations,
1634
       or null if no filters are to be applied. Each codec configuration
1635
       object MUST contain a "id" key identifying the codec to be used. */
1636
    /* Do filters key before compressor key so final filter chain is in correct order */
1637
0
    {
1638
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
1639
  if(var->filters == NULL) var->filters = (void*)nclistnew();
1640
  if(zvar->incompletefilters == NULL) zvar->incompletefilters = (void*)nclistnew();
1641
  chainindex = 0; /* track location of filter in the chain */
1642
  if((stat = NCZ_filter_initialize())) goto done;
1643
  if((stat = NCJdictget(jvar,"filters",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1644
  if(jvalue != NULL && NCJsort(jvalue) != NCJ_NULL) {
1645
      int k;
1646
      if(NCJsort(jvalue) != NCJ_ARRAY) {stat = NC_EFILTER; goto done;}
1647
      for(k=0;;k++) {
1648
    jfilter = NULL;
1649
    jfilter = NCJith(jvalue,k);
1650
    if(jfilter == NULL) break; /* done */
1651
    if(NCJsort(jfilter) != NCJ_DICT) {stat = NC_EFILTER; goto done;}
1652
    if((stat = NCZ_filter_build(file,var,jfilter,chainindex++))) goto done;
1653
      }
1654
  }
1655
#endif
1656
0
    }
1657
1658
    /* compressor key */
1659
    /* From V2 Spec: A JSON object identifying the primary compression codec and providing
1660
       configuration parameters, or ``null`` if no compressor is to be used. */
1661
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
1662
    { 
1663
  if(var->filters == NULL) var->filters = (void*)nclistnew();
1664
  if((stat = NCZ_filter_initialize())) goto done;
1665
  if((stat = NCJdictget(jvar,"compressor",&jfilter))<0) {stat = NC_EINVAL; goto done;}
1666
  if(jfilter != NULL && NCJsort(jfilter) != NCJ_NULL) {
1667
      if(NCJsort(jfilter) != NCJ_DICT) {stat = NC_EFILTER; goto done;}
1668
      if((stat = NCZ_filter_build(file,var,jfilter,chainindex++))) goto done;
1669
  }
1670
    }
1671
    /* Suppress variable if there are filters and var is not fixed-size */
1672
    if(varsized && nclistlength((NClist*)var->filters) > 0)
1673
  suppress = 1;
1674
#endif
1675
0
    if(zarr_rank > 0) {
1676
0
  if((stat = computedimrefs(file, var, purezarr, xarray, rank, dimnames, shapes, var->dim)))
1677
0
      goto done;
1678
0
  if(!zvar->scalar) {
1679
      /* Extract the dimids */
1680
0
      for(j=0;j<rank;j++)
1681
0
    var->dimids[j] = var->dim[j]->hdr.id;
1682
0
  }
1683
0
    }
1684
1685
#ifdef NETCDF_ENABLE_NCZARR_FILTERS
1686
    if(!suppress) {
1687
  /* At this point, we can finalize the filters */
1688
  if((stat = NCZ_filter_setup(var))) goto done;
1689
    }
1690
#endif
1691
1692
0
suppressvar:
1693
0
    if(suppress) {
1694
  /* Reclaim NCZarr variable specific info */
1695
0
  (void)NCZ_zclose_var1(var);
1696
  /* Remove from list of variables and reclaim the top level var object */
1697
0
  (void)nc4_var_list_del(grp, var);
1698
0
  var = NULL;
1699
0
    }
1700
1701
0
done:
1702
0
    nclistfreeall(dimnames); dimnames = NULL;
1703
0
    nullfree(shapes); shapes = NULL;
1704
0
    nullfree(key); key = NULL;
1705
0
    return ZUNTRACE(stat);
1706
0
}
1707
1708
/**
1709
 * @internal Materialize vars into memory;
1710
 * Take xarray and purezarr into account.
1711
 *
1712
 * @param file Pointer to file info struct.
1713
 * @param grp Pointer to grp info struct.
1714
 * @param varnames List of names of variables in this group
1715
 *
1716
 * @return ::NC_NOERR No error.
1717
 * @author Dennis Heimbigner
1718
 */
1719
static int
1720
define_vars(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* varnames)
1721
0
{
1722
0
    int stat = NC_NOERR;
1723
0
    size_t i;
1724
1725
0
    ZTRACE(3,"file=%s grp=%s |varnames|=%u",file->controller->path,grp->hdr.name,nclistlength(varnames));
1726
1727
    /* Load each var in turn */
1728
0
    for(i = 0; i < nclistlength(varnames); i++) {
1729
0
  const char* varname = (const char*)nclistget(varnames,i);
1730
0
        if((stat = define_var1(file,grp,varname))) goto done;
1731
0
  varname = nclistget(varnames,i);
1732
0
    }
1733
1734
0
done:
1735
0
    return ZUNTRACE(stat);
1736
0
}
1737
1738
/**
1739
 * @internal Materialize subgroups into memory
1740
 *
1741
 * @param file Pointer to file info struct.
1742
 * @param grp Pointer to grp info struct.
1743
 * @param subgrpnames List of names of subgroups in this group
1744
 *
1745
 * @return ::NC_NOERR No error.
1746
 * @author Dennis Heimbigner
1747
 */
1748
static int
1749
define_subgrps(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, NClist* subgrpnames)
1750
0
{
1751
0
    size_t i;
1752
0
    int stat = NC_NOERR;
1753
1754
0
    ZTRACE(3,"file=%s grp=%s |subgrpnames|=%u",file->controller->path,grp->hdr.name,nclistlength(subgrpnames));
1755
1756
    /* Load each subgroup name in turn */
1757
0
    for(i = 0; i < nclistlength(subgrpnames); i++) {
1758
0
  NC_GRP_INFO_T* g = NULL;
1759
0
  const char* gname = nclistget(subgrpnames,i);
1760
0
  char norm_name[NC_MAX_NAME];
1761
  /* Check and normalize the name. */
1762
0
  if((stat = nc4_check_name(gname, norm_name)))
1763
0
      goto done;
1764
0
  if((stat = nc4_grp_list_add(file, grp, norm_name, &g)))
1765
0
      goto done;
1766
0
  if(!(g->format_grp_info = calloc(1, sizeof(NCZ_GRP_INFO_T))))
1767
0
      {stat = NC_ENOMEM; goto done;}
1768
0
  ((NCZ_GRP_INFO_T*)g->format_grp_info)->common.file = file;
1769
0
    }
1770
1771
    /* Recurse to fill in subgroups */
1772
0
    for(i=0;i<ncindexsize(grp->children);i++) {
1773
0
  NC_GRP_INFO_T* g = (NC_GRP_INFO_T*)ncindexith(grp->children,i);
1774
0
  if((stat = define_grp(file,g)))
1775
0
      goto done;
1776
0
    }
1777
1778
0
done:
1779
0
    return ZUNTRACE(THROW(stat));
1780
0
}
1781
1782
1783
/**************************************************/
1784
/* Utilities */
1785
1786
static int
1787
parse_group_content(const NCjson* jcontent, NClist* dimdefs, NClist* varnames, NClist* subgrps)
1788
0
{
1789
0
    int stat = NC_NOERR;
1790
0
    size_t i;
1791
0
    const NCjson* jvalue = NULL;
1792
1793
0
    ZTRACE(3,"jcontent=|%s| |dimdefs|=%u |varnames|=%u |subgrps|=%u",NCJtotext(jcontent,0),(unsigned)nclistlength(dimdefs),(unsigned)nclistlength(varnames),(unsigned)nclistlength(subgrps));
1794
1795
0
    if((stat=dictgetalt(jcontent,"dimensions","dims",&jvalue))) goto done;
1796
0
    if(jvalue != NULL) {
1797
0
  if(NCJsort(jvalue) != NCJ_DICT) {stat = (THROW(NC_ENCZARR)); goto done;}
1798
  /* Extract the dimensions defined in this group */
1799
0
  for(i=0;i<NCJdictlength(jvalue);i++) {
1800
0
      const NCjson* jname = NCJdictkey(jvalue,i);
1801
0
      const NCjson* jleninfo = NCJdictvalue(jvalue,i);
1802
0
          const NCjson* jtmp = NULL;
1803
0
            const char* slen = "0";
1804
0
            const char* sunlim = "0";
1805
0
      char norm_name[NC_MAX_NAME + 1];
1806
      /* Verify name legality */
1807
0
      if((stat = nc4_check_name(NCJstring(jname), norm_name)))
1808
0
    {stat = NC_EBADNAME; goto done;}
1809
      /* check the length */
1810
0
            if(NCJsort(jleninfo) == NCJ_DICT) {
1811
0
    if((stat = NCJdictget(jleninfo,"size",&jtmp))<0) {stat = NC_EINVAL; goto done;}
1812
0
    if(jtmp== NULL)
1813
0
        {stat = NC_EBADNAME; goto done;}
1814
0
    slen = NCJstring(jtmp);
1815
    /* See if unlimited */
1816
0
    if((stat = NCJdictget(jleninfo,"unlimited",&jtmp))<0) {stat = NC_EINVAL; goto done;}
1817
0
          if(jtmp == NULL) sunlim = "0"; else sunlim = NCJstring(jtmp);
1818
0
            } else if(jleninfo != NULL && NCJsort(jleninfo) == NCJ_INT) {
1819
0
    slen = NCJstring(jleninfo);   
1820
0
      } else
1821
0
    {stat = NC_ENCZARR; goto done;}
1822
0
      nclistpush(dimdefs,strdup(norm_name));
1823
0
      nclistpush(dimdefs,strdup(slen));
1824
0
          nclistpush(dimdefs,strdup(sunlim));
1825
0
  }
1826
0
    }
1827
1828
0
    if((stat=dictgetalt(jcontent,"arrays","vars",&jvalue))) goto done;
1829
0
    if(jvalue != NULL) {
1830
  /* Extract the variable names in this group */
1831
0
  for(i=0;i<NCJarraylength(jvalue);i++) {
1832
0
      NCjson* jname = NCJith(jvalue,i);
1833
0
      char norm_name[NC_MAX_NAME + 1];
1834
      /* Verify name legality */
1835
0
      if((stat = nc4_check_name(NCJstring(jname), norm_name)))
1836
0
    {stat = NC_EBADNAME; goto done;}
1837
0
      nclistpush(varnames,strdup(norm_name));
1838
0
  }
1839
0
    }
1840
1841
0
    if((stat = NCJdictget(jcontent,"groups",&jvalue))<0) {stat = NC_EINVAL; goto done;}
1842
0
    if(jvalue != NULL) {
1843
  /* Extract the subgroup names in this group */
1844
0
  for(i=0;i<NCJarraylength(jvalue);i++) {
1845
0
      NCjson* jname = NCJith(jvalue,i);
1846
0
      char norm_name[NC_MAX_NAME + 1];
1847
      /* Verify name legality */
1848
0
      if((stat = nc4_check_name(NCJstring(jname), norm_name)))
1849
0
    {stat = NC_EBADNAME; goto done;}
1850
0
      nclistpush(subgrps,strdup(norm_name));
1851
0
  }
1852
0
    }
1853
1854
0
done:
1855
0
    return ZUNTRACE(THROW(stat));
1856
0
}
1857
1858
static int
1859
parse_group_content_pure(NCZ_FILE_INFO_T*  zinfo, NC_GRP_INFO_T* grp, NClist* varnames, NClist* subgrps)
1860
0
{
1861
0
    int stat = NC_NOERR;
1862
0
    char *key = NULL;
1863
1864
0
    ZTRACE(3,"zinfo=%s grp=%s |varnames|=%u |subgrps|=%u",zinfo->common.file->controller->path,grp->hdr.name,(unsigned)nclistlength(varnames),(unsigned)nclistlength(subgrps));
1865
1866
0
    if ((stat = NCZ_grpkey(grp,&key))){
1867
0
        goto done;
1868
0
    }
1869
0
    nclistclear(varnames);
1870
0
    nclistclear(subgrps);
1871
0
    if((stat = NCZMD_list_nodes(zinfo, key, subgrps, varnames))) goto done;
1872
1873
0
done:
1874
0
    nullfree(key);
1875
0
    return ZUNTRACE(THROW(stat));
1876
0
}
1877
1878
/* Convert a list of integer strings to 64 bit dimension sizes (shapes) */
1879
static int
1880
decodeints(const NCjson* jshape, size64_t* shapes)
1881
0
{
1882
0
    int stat = NC_NOERR;
1883
0
    size_t i;
1884
1885
0
    for(i=0;i<NCJarraylength(jshape);i++) {
1886
0
  struct ZCVT zcvt;
1887
0
  nc_type typeid = NC_NAT;
1888
0
  NCjson* jv = NCJith(jshape,i);
1889
0
  if((stat = NCZ_json2cvt(jv,&zcvt,&typeid))) goto done;
1890
0
  switch (typeid) {
1891
0
  case NC_INT64:
1892
0
  if(zcvt.int64v < 0) {stat = (THROW(NC_ENCZARR)); goto done;}
1893
0
      shapes[i] = (size64_t)zcvt.int64v;
1894
0
      break;
1895
0
  case NC_UINT64:
1896
0
      shapes[i] = (size64_t)zcvt.uint64v;
1897
0
      break;
1898
0
  default: {stat = (THROW(NC_ENCZARR)); goto done;}
1899
0
  }
1900
0
    }
1901
1902
0
done:
1903
0
    return THROW(stat);
1904
0
}
1905
1906
/* This code is a subset of NCZ_def_dim */
1907
static int
1908
createdim(NC_FILE_INFO_T* file, NC_GRP_INFO_T* grp, const char* name, size64_t dimlen, NC_DIM_INFO_T** dimp)
1909
0
{
1910
0
    int stat = NC_NOERR;
1911
0
    NC_DIM_INFO_T* thed = NULL;
1912
0
    if(grp == NULL) grp = file->root_grp;
1913
1914
0
    if((stat = nc4_dim_list_add(grp, name, (size_t)dimlen, -1, &thed)))
1915
0
        goto done;
1916
0
    assert(thed != NULL);
1917
    /* Create struct for NCZ-specific dim info. */
1918
0
    if (!(thed->format_dim_info = calloc(1, sizeof(NCZ_DIM_INFO_T))))
1919
0
  {stat = NC_ENOMEM; goto done;}
1920
0
    ((NCZ_DIM_INFO_T*)thed->format_dim_info)->common.file = file;
1921
0
    *dimp = thed; thed = NULL;
1922
0
done:
1923
0
    return stat;
1924
0
}
1925
1926
1927
/*
1928
Given a list of segments, find corresponding group.
1929
*/
1930
static int
1931
locategroup(NC_FILE_INFO_T* file, size_t nsegs, NClist* segments, NC_GRP_INFO_T** grpp)
1932
0
{
1933
0
    size_t i, j;
1934
0
    int found, stat = NC_NOERR;
1935
0
    NC_GRP_INFO_T* grp = NULL;
1936
1937
0
    grp = file->root_grp;
1938
0
    for(i=0;i<nsegs;i++) {
1939
0
  const char* segment = nclistget(segments,i);
1940
0
  char norm_name[NC_MAX_NAME];
1941
0
  found = 0;
1942
0
  if((stat = nc4_check_name(segment,norm_name))) goto done;
1943
0
  for(j=0;j<ncindexsize(grp->children);j++) {
1944
0
      NC_GRP_INFO_T* subgrp = (NC_GRP_INFO_T*)ncindexith(grp->children,j);
1945
0
      if(strcmp(subgrp->hdr.name,norm_name)==0) {
1946
0
    grp = subgrp;
1947
0
    found = 1;
1948
0
    break;
1949
0
      }
1950
0
  }
1951
0
  if(!found) {stat = NC_ENOGRP; goto done;}
1952
0
    }
1953
    /* grp should be group of interest */
1954
0
    if(grpp) *grpp = grp;
1955
1956
0
done:
1957
0
    return THROW(stat);
1958
0
}
1959
1960
static int
1961
parsedimrefs(NC_FILE_INFO_T* file, NClist* dimnames, size64_t* shape, NC_DIM_INFO_T** dims, int create)
1962
0
{
1963
0
    size_t i;
1964
0
    int stat = NC_NOERR;
1965
0
    NClist* segments = NULL;
1966
1967
0
    for(i=0;i<nclistlength(dimnames);i++) {
1968
0
  NC_GRP_INFO_T* g = NULL;
1969
0
  NC_DIM_INFO_T* d = NULL;
1970
0
  size_t j;
1971
0
  const char* dimpath = nclistget(dimnames,i);
1972
0
  const char* dimname = NULL;
1973
1974
  /* Locate the corresponding NC_DIM_INFO_T* object */
1975
0
  nclistfreeall(segments);
1976
0
  segments = nclistnew();
1977
0
  if((stat = ncz_splitkey(dimpath,segments)))
1978
0
      goto done;
1979
0
  if((stat=locategroup(file,nclistlength(segments)-1,segments,&g)))
1980
0
      goto done;
1981
  /* Lookup the dimension */
1982
0
  dimname = nclistget(segments,nclistlength(segments)-1);
1983
0
  d = NULL;
1984
0
  dims[i] = NULL;
1985
0
  for(j=0;j<ncindexsize(g->dim);j++) {
1986
0
      d = (NC_DIM_INFO_T*)ncindexith(g->dim,j);
1987
0
      if(strcmp(d->hdr.name,dimname)==0) {
1988
0
    dims[i] = d;
1989
0
    break;
1990
0
      }
1991
0
  }
1992
0
  if(dims[i] == NULL && create) {
1993
      /* If not found and create then create it */
1994
0
      if((stat = createdim(file, g, dimname, shape[i], &dims[i])))
1995
0
          goto done;
1996
0
  } else {
1997
      /* Verify consistency */
1998
0
      if(dims[i]->len != shape[i])
1999
0
          {stat = NC_EDIMSIZE; goto done;}
2000
0
  }
2001
0
  assert(dims[i] != NULL);
2002
0
    }
2003
0
done:
2004
0
    nclistfreeall(segments);
2005
0
    return THROW(stat);
2006
0
}
2007
2008
/**
2009
 * @internal Get the metadata for a variable.
2010
 *
2011
 * @param var Pointer to var info struct.
2012
 *
2013
 * @return ::NC_NOERR No error.
2014
 * @return ::NC_EBADID Bad ncid.
2015
 * @return ::NC_ENOMEM Out of memory.
2016
 * @return ::NC_EHDFERR HDF5 returned error.
2017
 * @return ::NC_EVARMETA Error with var metadata.
2018
 * @author Ed Hartnett
2019
 */
2020
int
2021
ncz_get_var_meta(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var)
2022
0
{
2023
0
    int retval = NC_NOERR;
2024
2025
0
    assert(file && var && var->format_var_info);
2026
0
    LOG((3, "%s: var %s", __func__, var->hdr.name));
2027
0
    ZTRACE(3,"file=%s var=%s",file->controller->path,var->hdr.name);
2028
    
2029
    /* Have we already read the var metadata? */
2030
0
    if (var->meta_read)
2031
0
  goto done;
2032
2033
#ifdef LOOK
2034
    /* Get the current chunk cache settings. */
2035
    if ((access_pid = H5Dget_access_plist(hdf5_var->hdf_datasetid)) < 0)
2036
  BAIL(NC_EVARMETA);
2037
2038
    /* Learn about current chunk cache settings. */
2039
    if ((H5Pget_chunk_cache(access_pid, &(var->chunk_cache_nelems),
2040
          &(var->chunk_cache_size), &rdcc_w0)) < 0)
2041
  BAIL(NC_EHDFERR);
2042
    var->chunk_cache_preemption = rdcc_w0;
2043
2044
    /* Get the dataset creation properties. */
2045
    if ((propid = H5Dget_create_plist(hdf5_var->hdf_datasetid)) < 0)
2046
  BAIL(NC_EHDFERR);
2047
2048
    /* Get var chunking info. */
2049
    if ((retval = get_chunking_info(propid, var)))
2050
  BAIL(retval);
2051
2052
    /* Get filter info for a var. */
2053
    if ((retval = get_filter_info(propid, var)))
2054
  BAIL(retval);
2055
2056
    /* Get fill value, if defined. */
2057
    if ((retval = get_fill_info(propid, var)))
2058
  BAIL(retval);
2059
2060
    /* Is this a deflated variable with a chunksize greater than the
2061
     * current cache size? */
2062
    if ((retval = nc4_adjust_var_cache(var)))
2063
  BAIL(retval);
2064
2065
    /* Is there an attribute which means quantization was used? */
2066
    if ((retval = get_quantize_info(var)))
2067
  BAIL(retval);
2068
2069
    if (var->coords_read && !var->dimscale)
2070
  if ((retval = get_attached_info(var, hdf5_var, var->ndims, hdf5_var->hdf_datasetid)))
2071
      goto done;;
2072
#endif
2073
2074
    /* Remember that we have read the metadata for this var. */
2075
0
    var->meta_read = NC_TRUE;
2076
0
done:
2077
0
    return ZUNTRACE(retval);
2078
0
}
2079
2080
/* Compute the set of dim refs for this variable, taking purezarr and xarray into account */
2081
static int
2082
computedimrefs(NC_FILE_INFO_T* file, NC_VAR_INFO_T* var, int purezarr, int xarray, int ndims, NClist* dimnames, size64_t* shapes, NC_DIM_INFO_T** dims)
2083
0
{
2084
0
    int stat = NC_NOERR;
2085
0
    size_t i;
2086
0
    int createdims = 0; /* 1 => we need to create the dims in current group
2087
                                if they do not already exist */
2088
0
    NCZ_FILE_INFO_T* zfile = (NCZ_FILE_INFO_T*)file->format_file_info;
2089
0
    NCZ_VAR_INFO_T* zvar = (NCZ_VAR_INFO_T*)(var->format_var_info);
2090
0
    NCjson* jatts = NULL;
2091
0
    NC_GRP_INFO_T* grp = var->container; /* Immediate parent group for var */
2092
0
    char* grpfqn = NULL; /* FQN for grp */
2093
2094
0
    ZTRACE(3,"file=%s var=%s purezarr=%d xarray=%d ndims=%d shape=%s",
2095
0
      file->controller->path,var->hdr.name,purezarr,xarray,(int)ndims,nczprint_vector(ndims,shapes));
2096
0
    assert(zfile && zvar);
2097
2098
0
    if(purezarr && xarray) {/* Read in the attributes to get xarray dimdef attribute; Note that it might not exist */
2099
  /* Note that if xarray && !purezarr, then xarray will be superseded by the nczarr dimensions key */
2100
0
        char zdimname[4096];
2101
0
  if(zvar->xarray == NULL) {
2102
0
      assert(nclistlength(dimnames) == 0);
2103
0
      if((stat = ncz_read_atts(file,(NC_OBJ*)var))) goto done;
2104
0
  }
2105
0
  if(zvar->xarray != NULL) {
2106
0
      size_t len;
2107
      /* get the FQN of the current group */
2108
0
      if((stat = NCZ_grpkey(grp, &grpfqn))) goto done;
2109
0
      assert(grpfqn != NULL);
2110
0
      len = strlen(grpfqn);
2111
0
      assert(len > 0);
2112
      /* supress any trailing '/' */
2113
0
      if(grpfqn[len - 1] == '/') grpfqn[len -1] = '\0';
2114
      /* convert xarray to FQN dimnames */
2115
0
      for(i=0;i<nclistlength(zvar->xarray);i++) {
2116
0
          snprintf(zdimname,sizeof(zdimname),"%s/%s",grpfqn,(const char*)nclistget(zvar->xarray,i));
2117
0
          nclistpush(dimnames,strdup(zdimname));
2118
0
      }
2119
0
  }
2120
0
  createdims = 1; /* may need to create them */
2121
0
    }
2122
2123
    /* If pure zarr and we have no dimref names, then fake it */
2124
    /* Note that to avoid creating duplicates of anonymous dims, we create dim in root group */
2125
0
    if(purezarr && nclistlength(dimnames) == 0) {
2126
0
  int i;
2127
0
  createdims = 1;
2128
0
        for(i=0;i<ndims;i++) {
2129
      /* Compute the set of absolute paths to dimrefs */
2130
0
            char zdimname[4096];
2131
0
      snprintf(zdimname,sizeof(zdimname),"/%s_%llu",NCDIMANON,shapes[i]);
2132
0
      nclistpush(dimnames,strdup(zdimname));
2133
0
  }
2134
0
    }
2135
2136
    /* Now, use dimnames to get the dims; create if necessary */
2137
0
    if((stat = parsedimrefs(file,dimnames,shapes,dims,createdims)))
2138
0
        goto done;
2139
2140
0
done:
2141
0
    nullfree(grpfqn);
2142
0
    NCJreclaim(jatts);
2143
0
    return ZUNTRACE(THROW(stat));
2144
0
}
2145
2146
/**
2147
Implement the JSON convention:
2148
Stringify it as the value and make the attribute be of type "char".
2149
*/
2150
2151
static int
2152
json_convention_read(const NCjson* json, NCjson** jtextp)
2153
0
{
2154
0
    int stat = NC_NOERR;
2155
0
    NCjson* jtext = NULL;
2156
0
    char* text = NULL;
2157
2158
0
    if(json == NULL) {stat = NC_EINVAL; goto done;}
2159
0
    if(NCJunparse(json,0,&text)) {stat = NC_EINVAL; goto done;}
2160
0
    NCJnewstring(NCJ_STRING,text,&jtext);
2161
0
    *jtextp = jtext; jtext = NULL;
2162
0
done:
2163
0
    NCJreclaim(jtext);
2164
0
    nullfree(text);
2165
0
    return stat;
2166
0
}
2167
2168
#if 0
2169
/**
2170
Implement the JSON convention:
2171
Parse it as JSON and use that as its value in .zattrs.
2172
*/
2173
static int
2174
json_convention_write(size_t len, const void* data, NCjson** jsonp, int* isjsonp)
2175
{
2176
    int stat = NC_NOERR;
2177
    NCjson* jexpr = NULL;
2178
    int isjson = 0;
2179
2180
    assert(jsonp != NULL);
2181
    if(NCJparsen(len,(char*)data,0,&jexpr)) {
2182
  /* Ok, just treat as sequence of chars */
2183
  NCJnewstringn(NCJ_STRING, len, data, &jexpr);
2184
    }
2185
    isjson = 1;
2186
    *jsonp = jexpr; jexpr = NULL;
2187
    if(isjsonp) *isjsonp = isjson;
2188
done:
2189
    NCJreclaim(jexpr);
2190
    return stat;
2191
}
2192
#endif
2193
2194
#if 0
2195
/* Convert an attribute "types list to an envv style list */
2196
static int
2197
jtypes2atypes(NCjson* jtypes, NClist* atypes)
2198
{
2199
    int stat = NC_NOERR;
2200
    size_t i;
2201
    for(i=0;i<NCJdictlength(jtypes);i++) {
2202
  const NCjson* key = NCJdictkey(jtypes,i);
2203
  const NCjson* value = NCJdictvalue(jtypes,i);
2204
  if(NCJsort(key) != NCJ_STRING) {stat = (THROW(NC_ENCZARR)); goto done;}
2205
  if(NCJsort(value) != NCJ_STRING) {stat = (THROW(NC_ENCZARR)); goto done;}
2206
  nclistpush(atypes,strdup(NCJstring(key)));
2207
  nclistpush(atypes,strdup(NCJstring(value)));
2208
    }
2209
done:
2210
    return stat;
2211
}
2212
#endif
2213
2214
/* See if there is reason to believe the specified path is a legitimate (NC)Zarr file
2215
 * Do a breadth first walk of the tree starting at file path.
2216
 * @param file to validate
2217
 * @return NC_NOERR if it looks ok
2218
 * @return NC_ENOTNC if it does not look ok
2219
 */
2220
static int
2221
ncz_validate(NC_FILE_INFO_T* file)
2222
0
{
2223
0
    int stat = NC_NOERR;
2224
0
    NCZ_FILE_INFO_T* zinfo = (NCZ_FILE_INFO_T*)file->format_file_info;
2225
0
    int validate = 0;
2226
0
    NCbytes* prefix = ncbytesnew();
2227
0
    NClist* queue = nclistnew();
2228
0
    NClist* nextlevel = nclistnew();
2229
0
    NCZMAP* map = zinfo->map;
2230
0
    char* path = NULL;
2231
0
    char* segment = NULL;
2232
0
    size_t seglen;
2233
0
      
2234
0
    ZTRACE(3,"file=%s",file->controller->path);
2235
0
2236
0
    path = strdup("/");
2237
0
    nclistpush(queue,path);
2238
0
    path = NULL;
2239
0
    do {
2240
0
        nullfree(path); path = NULL;
2241
0
  /* This should be full path key */
2242
0
  path = nclistremove(queue,0); /* remove from front of queue */
2243
0
  /* get list of next level segments (partial keys) */
2244
0
  assert(nclistlength(nextlevel)==0);
2245
0
        if((stat=nczmap_search(map,path,nextlevel))) {validate = 0; goto done;}
2246
0
        /* For each s in next level, test, convert to full path, and push onto queue */
2247
0
  while(nclistlength(nextlevel) > 0) {
2248
0
            segment = nclistremove(nextlevel,0);
2249
0
            seglen = nulllen(segment);
2250
0
      if((seglen >= 2 && memcmp(segment,".z",2)==0) || (seglen >= 4 && memcmp(segment,".ncz",4)==0)) {
2251
0
    validate = 1;
2252
0
          goto done;
2253
0
       }
2254
0
       /* Convert to full path */
2255
0
       ncbytesclear(prefix);
2256
0
       ncbytescat(prefix,path);
2257
0
       if(strlen(path) > 1) ncbytescat(prefix,"/");
2258
0
       ncbytescat(prefix,segment);
2259
0
       /* push onto queue */
2260
0
       nclistpush(queue,ncbytesextract(prefix));
2261
0
       nullfree(segment); segment = NULL;
2262
0
   }
2263
0
    } while(nclistlength(queue) > 0);
2264
0
done:
2265
0
    if(!validate) stat = NC_ENOTNC;
2266
0
    nullfree(path);
2267
0
    nullfree(segment);
2268
0
    nclistfreeall(queue);
2269
0
    nclistfreeall(nextlevel);
2270
0
    ncbytesfree(prefix);
2271
0
    return ZUNTRACE(THROW(stat));
2272
0
}
2273
2274
/**
2275
Insert an attribute into a list of attribute, including typing
2276
Takes control of javalue.
2277
@param jatts
2278
@param jtypes
2279
@param aname
2280
@param javalue
2281
*/
2282
static int
2283
insert_attr(NCjson* jatts, NCjson* jtypes, const char* aname, NCjson* javalue, const char* atype)
2284
0
{
2285
0
    int stat = NC_NOERR;
2286
0
    if(jatts != NULL) {
2287
0
  if(jtypes != NULL) {
2288
0
            NCJinsertstring(jtypes,aname,atype);
2289
0
  }
2290
0
        NCJinsert(jatts,aname,javalue);
2291
0
    }
2292
0
    return THROW(stat);
2293
0
}
2294
2295
/**
2296
Insert _nczarr_attr into .zattrs
2297
Take control of jtypes
2298
@param jatts
2299
@param jtypes
2300
*/
2301
static int
2302
insert_nczarr_attr(NCjson* jatts, NCjson* jtypes)
2303
0
{
2304
0
    NCjson* jdict = NULL;
2305
0
    if(jatts != NULL && jtypes != NULL) {
2306
0
  NCJinsertstring(jtypes,NCZ_V2_ATTR,"|J0"); /* type for _nczarr_attr */
2307
0
        NCJnew(NCJ_DICT,&jdict);
2308
0
        NCJinsert(jdict,"types",jtypes);
2309
0
        NCJinsert(jatts,NCZ_V2_ATTR,jdict);
2310
0
        jdict = NULL;
2311
0
    }
2312
0
    return NC_NOERR;
2313
0
}
2314
2315
/**
2316
Upload a .zattrs object
2317
Optionally take control of jatts and jtypes
2318
@param file
2319
@param container
2320
@param jattsp
2321
@param jtypesp
2322
*/
2323
static int
2324
upload_attrs(NC_FILE_INFO_T* file, NC_OBJ* container, NCjson* jatts)
2325
0
{
2326
0
    int stat = NC_NOERR;
2327
0
    NCZ_FILE_INFO_T* zinfo = NULL;
2328
0
    NC_VAR_INFO_T* var = NULL;
2329
0
    NC_GRP_INFO_T* grp = NULL;
2330
0
    NCZMAP* map = NULL;
2331
0
    char* fullpath = NULL;
2332
0
    char* key = NULL;
2333
0
2334
0
    ZTRACE(3,"file=%s grp=%s",file->controller->path,container->name);
2335
0
2336
0
    if(jatts == NULL) goto done;    
2337
0
2338
0
    zinfo = file->format_file_info;
2339
0
    map = zinfo->map;
2340
0
2341
0
    if(container->sort == NCVAR) {
2342
0
        var = (NC_VAR_INFO_T*)container;
2343
0
    } else if(container->sort == NCGRP) {
2344
0
        grp = (NC_GRP_INFO_T*)container;
2345
0
    }
2346
0
2347
0
    /* Construct container path */
2348
0
    if(container->sort == NCGRP)
2349
0
  stat = NCZ_grpkey(grp,&fullpath);
2350
0
    else
2351
0
  stat = NCZ_varkey(var,&fullpath);
2352
0
    if(stat) goto done;
2353
0
2354
0
    /* write .zattrs*/
2355
0
    if((stat = nczm_concat(fullpath,Z2ATTRS,&key))) goto done;
2356
0
    if((stat=NCZ_uploadjson(map,key,jatts))) goto done;
2357
0
    nullfree(key); key = NULL;
2358
0
2359
0
done:
2360
0
    nullfree(fullpath);
2361
0
    return ZUNTRACE(THROW(stat));
2362
0
}
2363
2364
#if 0
2365
/**
2366
@internal Get contents of a meta object; fail it it does not exist
2367
@param zmap - [in] map
2368
@param key - [in] key of the object
2369
@param jsonp - [out] return parsed json || NULL if not exists
2370
@return NC_NOERR
2371
@return NC_EXXX
2372
@author Dennis Heimbigner
2373
*/
2374
static int
2375
readarray(NCZMAP* zmap, const char* key, NCjson** jsonp)
2376
{
2377
    int stat = NC_NOERR;
2378
    NCjson* json = NULL;
2379
2380
    if((stat = NCZ_downloadjson(zmap,key,&json))) goto done;
2381
    if(json != NULL && NCJsort(json) != NCJ_ARRAY) {stat = NC_ENCZARR; goto done;}
2382
    if(jsonp) {*jsonp = json; json = NULL;}
2383
done:
2384
    NCJreclaim(json);
2385
    return stat;
2386
}
2387
#endif
2388
2389
/* Get one of two key values from a dict */
2390
static int
2391
dictgetalt(const NCjson* jdict, const char* name, const char* alt, const NCjson** jvaluep)
2392
0
{
2393
0
    int stat = NC_NOERR;
2394
0
    const NCjson* jvalue = NULL;
2395
0
    if((stat = NCJdictget(jdict,name,&jvalue))<0) {stat = NC_EINVAL; goto done;} /* try this first */
2396
0
    if(jvalue == NULL) {
2397
0
        if((stat = NCJdictget(jdict,alt,&jvalue))<0) {stat = NC_EINVAL; goto done;} /* try this alternative*/
2398
0
    }
2399
0
    if(jvaluep) *jvaluep = jvalue;
2400
0
done:
2401
0
    return THROW(stat);
2402
0
}
2403
2404
/* Get _nczarr_xxx from either .zXXX or .zattrs */
2405
static int
2406
getnczarrkey(NC_OBJ* container, const char* name, const NCjson** jncxxxp)
2407
0
{
2408
0
    int stat = NC_NOERR;
2409
0
    const NCjson* jxxx = NULL;
2410
0
    NC_GRP_INFO_T* grp = NULL;
2411
0
    NC_VAR_INFO_T* var = NULL;
2412
0
    struct ZARROBJ* zobj = NULL;
2413
2414
    /* Decode container */
2415
0
    if(container->sort == NCGRP) {
2416
0
  grp = (NC_GRP_INFO_T*)container;
2417
0
  zobj = &((NCZ_GRP_INFO_T*)grp->format_grp_info)->zgroup;
2418
0
    } else {
2419
0
  var = (NC_VAR_INFO_T*)container;
2420
0
  zobj = &((NCZ_VAR_INFO_T*)var->format_var_info)->zarray;
2421
0
    }
2422
2423
    /* Try .zattrs first */
2424
0
    if(zobj->atts != NULL) {
2425
0
  jxxx = NULL;
2426
0
        if((stat = NCJdictget(zobj->atts,name,&jxxx))<0) {stat = NC_EINVAL; goto done;}
2427
0
    }
2428
0
    if(jxxx == NULL) {
2429
        /* Try .zxxx second */
2430
0
  if(zobj->obj != NULL) {
2431
0
            if((stat = NCJdictget(zobj->obj,name,&jxxx))<0) {stat = NC_EINVAL; goto done;}
2432
0
  }
2433
0
  if(jxxx != NULL)
2434
0
        zobj->nczv1 = 1; /* Mark as old style with _nczarr_xxx in obj not attributes */
2435
0
    }
2436
0
    if(jncxxxp) *jncxxxp = jxxx;
2437
0
done:
2438
0
    return THROW(stat);
2439
0
}
2440
2441
static int
2442
downloadzarrobj(NC_FILE_INFO_T* file, struct ZARROBJ* zobj, const char* fullpath, const char* objname)
2443
0
{
2444
0
    int stat = NC_NOERR;
2445
0
    char* key = NULL;
2446
0
    NCZMAP* map = ((NCZ_FILE_INFO_T*)file->format_file_info)->map;
2447
0
2448
0
    /* Download .zXXX and .zattrs */
2449
0
    nullfree(zobj->prefix);
2450
0
    zobj->prefix = strdup(fullpath);
2451
0
    NCJreclaim(zobj->obj); zobj->obj = NULL;
2452
0
    NCJreclaim(zobj->atts); zobj->obj = NULL;
2453
0
    if((stat = nczm_concat(fullpath,objname,&key))) goto done;
2454
0
    if((stat=NCZ_downloadjson(map,key,&zobj->obj))) goto done;
2455
0
    nullfree(key); key = NULL;
2456
0
    if((stat = nczm_concat(fullpath,Z2ATTRS,&key))) goto done;
2457
0
    if((stat=NCZ_downloadjson(map,key,&zobj->atts))) goto done;
2458
0
done:
2459
0
    nullfree(key);
2460
0
    return THROW(stat);
2461
0
}